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.

The FirstOrDefault method

The FirstOrDefault method

- There is a potential problem with the example I showed you in the last example. Problem comes if you have a sequence that is empty has no elements in it. In that case if you call first or last, they're going to throw an exception. So what you want to do instead, is, if you think that's possible, if you think you might have an empty sequence, then you want to call first or default, or last or default. And what they do is, they'll either return the first item that it finds, and if you have an empty sequence, then it will look up the default value for the data type and return that instead. So, in my case, let's take a look here, we've got, a filled list of integers, then I've got an empty list of integers, empty list of strings, and an empty list of Boolean values. When I run this, the first result is 50, because that's the first item and this list events. The next result is zero because that is an empty list of…

Contents