LINQ XOrDefault Methods
Prevent a NullReferenceException when working with LINQ XOrDefault methods.
We'll cover the following...
We get a NullReferenceException
when we use the properties or methods of an uninitialized object reference. We can also get a NullReferenceException
when working with the LINQ FirstOrDefault()
, LastOrDefault()
, and SingleOrDefault()
methods.
Finding one element of a collection
LINQ is a set of methods to filter, group, and order collections. Let’s focus on only the XOrDefault
methods.
The FirstOrDefault()
method finds the first element of a collection or the first element matching a condition. If the collection is empty or doesn’t have matching elements, FirstOrDefault()
returns the default value of the collection’s type. For reference types, that’s a null
. And we know what happens if we access a method or property on a reference that’s null
.
For example, let’s find the first movie with a high and low rating in our catalog.
var movies = new List<Movie>{new Movie("Shrek", 2001, 7.95f),new Movie("Inside Out", 2015, 8.2f),new Movie("Ratatouille", 2007, 8.1f),new Movie("Toy Story", 1995, 8.3f),new Movie("Cloudy with a Chance of Meatballs", 2009, 6.9f)};var withAGoodRating = movies.FirstOrDefault(movie => movie.Rating > 8.0);Console.WriteLine(withAGoodRating == null); // falsevar withLowRating = movies.FirstOrDefault(movie => movie.Rating < 6.0);Console.WriteLine(withLowRating == null); // trueConsole.WriteLine(withLowRating.Name);// If we forget to check for nulls after using FirstOrDefault,// it will break with the NullReferenceExceptionrecord Movie(string Name, int ReleaseYear, float Rating);
Notice we used FirstOrDefault()
to find the first movie with a ...