Getting the last element from a sequence with LINQ C#

Exercises in .NET with Andras Nemes

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.

View original post


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s