From the course: .NET Essentials: Working with LINQ

Unlock this course with a free trial

Join today to access over 22,600 courses taught by industry experts.

First and Last methods

First and Last methods

- All of the query operators we're looking at in this chapter are responsible for looking at a sequence of items and returning a single value. Now you can do this with a WHERE clause, if you have a condition that returns only one of the items in the list meets the criteria for the predicate, that's easy to do, but the idea here is that you only want to get a single item and you don't want to write a WHERE clause to do that. We're going to look at first, last, element at, and single in this chapter. And we start with first and last, which as the name suggests, return the first and last item in a sequence. And they're quite easy to do. I'm using the extension methods to do this. You can't use the query expressions to run this type of code. So, here, I've got a list of numbers and I'm calling first and last and getting first value is 50 and the last value is five. Now let's say, that I want to perform some other…

Contents