Using LINQ Last to Select Single Data
LINQ
26 Articles
In this article, let's learn about how to use Last and LastOrDefault in LINQ in .NET.
Note: If you have not done so already, I recommend you read the article on Using LINQ First to Select Single Data in Collections.
Table of Contents
- Introduction
- Search backward for an element using Last
- Search backward for an element using LastOrDefault
- When to use which?
- Summary
Introduction
We can select single piece of data from a collection using LINQ. We're going to use Last() and LastOrDefault() methods. Let's take a look at each of these methods and how they work.
Search backward for an element using Last
When searching, some of the methods will actually throw an exception if you don't find anything based on the expression. So, for example, first, you pass in your lambda expression of what you're looking for. It searches backward in the collection and finds that last one that matches the expression and returns that. If it doesn't find it, it throws an exception.
Code Sample - LINQ Last
Search backward for an element using LastOrDefault
The LastOrDefault, You pass in a lambda expression of what you're looking for, as well as an optional default value. It searches backwards in the collection, so it starts at the end of the collection and searches backwards, returns null if the values are not found based on the expression, or if you supply a default value, it will return that.
Code Sample - LINQ LastOrDefault
When to use which?
So now I've shown you all these LINQ queries, but which ones do you use and when do you use them? So I'm going to do a comparison between the Last() versus the LastOrDefault() methods. If you expect the element to be present in the collection, you can use Last(). But if you're not sure if that element is present, then use LastOrDefault(), and that has to do with exceptions, right? Because the Last() is going to throw an exception if something is not found. So if you want to handle that or maybe rethrow an exception if something's not found, you could use Last(). Me, I'd rather not deal with exceptions, so I really prefer LastOrDefault(). Also, this gives us back a null or some other default value, I find it easier to check for null than actually check for an exception.
Summary
In this article we learn't how to locate single data within collection using Last and LastOrDefault. We saw that there's an option to supply your own default value, that sometimes you need to catch exceptions or sometimes you need to check for null or that default value, depending on the method that you're calling. Now I always like using all the OrDefault() methods so that I can avoid anybody throwing exceptions. To me, throwing exceptions are not something that you want to use as a regular way of programming. Those should be exceptions. All these can be used with any IEnumerable or IQueryable types.