[Don’t .NET] Last() at last!
1 min readJan 11, 2025
Although LinkedLists may not be your go-to data structure, you might find yourself using the Last
property to access the tail of the list like this:
LinkedList<int> list = [];
LinkedListNode<int> lastNode = list.Last;
Console.WriteLine(lastNode);//Outputs nothing, since list.Last is null
However, you can also use the Last()
method, which will throw an InvalidOperationException
if the list is empty:
LinkedList<int> list = [];
int lastValue = list.Last();//Throws InvalidOperationException: Sequence contains no elements
Console.WriteLine(lastValue);
If the list contains elements, Last()
will return the last element's value:
LinkedList<int> list = [];
list.AddLast(0);
int lastValue = list.Last();
Console.WriteLine(lastValue);//Outputs 0
This behavior is explained by the fact that the Last
property of LinkedList
and the Last
method from LINQ are different. While it can be a bit convoluted, understanding this distinction is crucial for effective usage.