Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the last element in a List<>?

Tags:

c#

list

People also ask

What index identifies the last element in a list?

The index - 1 identifies the last element in a list. In slicing, if the end index specifies a position beyond the end of the list, Python will use the length of the list instead.

How do you get the last element in a Python list with negative indexing?

To access the last element of a Python list, use the indexing notation list[-1] with negative index -1 which points to the last list element. To access the second-, third-, and fourth-last elements, use the indices -2 , -3 , and -4 .


To get the last item of a collection use LastOrDefault() and Last() extension methods

var lastItem = integerList.LastOrDefault();

OR

var lastItem = integerList.Last();

Remeber to add using System.Linq;, or this method won't be available.


If you just want to access the last item in the list you can do

if(integerList.Count>0)
{
   //  pre C#8.0 : var item = integerList[integerList.Count - 1];
   //  C#8.0 : 
   var item = integerList[^1];
}

to get the total number of items in the list you can use the Count property

var itemCount = integerList.Count;

In C# 8.0 you can get the last item with ^ operator full explanation

List<char> list = ...;
var value = list[^1]; 

// Gets translated to 
var value = list[list.Count - 1];

Lets get at the root of the question, how to address the last element of a List safely...

Assuming

List<string> myList = new List<string>();

Then

//NOT safe on an empty list!
string myString = myList[myList.Count -1];

//equivalent to the above line when Count is 0, bad index
string otherString = myList[-1];

"count-1" is a bad habit unless you first guarantee the list is not empty.

There is not a convenient way around checking for the empty list except to do it.

The shortest way I can think of is

string myString = (myList.Count != 0) ? myList [ myList.Count-1 ] : "";

you could go all out and make a delegate that always returns true, and pass it to FindLast, which will return the last value (or default constructed valye if the list is empty). This function starts at the end of the list so will be Big O(1) or constant time, despite the method normally being O(n).

//somewhere in your codebase, a strange delegate is defined
private static bool alwaysTrue(string in)
{
    return true;
}

//Wherever you are working with the list
string myString = myList.FindLast(alwaysTrue);

The FindLast method is ugly if you count the delegate part, but it only needs to be declared one place. If the list is empty, it will return a default constructed value of the list type "" for string. Taking the alwaysTrue delegate a step further, making it a template instead of string type, would be more useful.


int lastInt = integerList[integerList.Count-1];