Say you have the following object sequence:
If you just want to get the very last element from this sequence with no query then you can use the Last operator:
This will select David Bowie from the list. You can also send an item selector to get the last element which matches the query:
…which returns Chuck Berry.
A caveat is that the Last operator throws an InvalidOperationException if there’s no single matching record:
To avoid this scenario you can use the LastOrDefault operator which returns the default value of the required object if there’s no matching one. Therefore “singer” in the above example will be null:
…which yields “No such singer”.
You can view all LINQ-related posts on this blog here.