LINQ XOrDefault Methods

Prevent a NullReferenceException when working with LINQ XOrDefault methods.

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.

Get hands-on with 1200+ tech skills courses.