A nice new overload is coming to LINQ's OrDefault methods (e.g. FirstOrDefault()), so let's check it out!

Current Implementation

In prior versions of .NET, we could use methods such as FirstOrDefault() to specify that we wanted the first element in a collection, or the default value of the element's type.

var numbers = new List<int>() { 7, 1, 9, 41, 8, 22 };
var firstNumber = numbers.FirstOrDefault(); //7
var matchingFirstNumber = numbers.FirstOrDefault(x => x > 30); //41
var missingFirstNumber = numbers.FirstOrDefault(x => x > 50); //0

var otherNumbers = new List<int>();
var otherFirstNumber = otherNumbers.FirstOrDefault(); //0

There are also other methods such as SingleOrDefault(), which returns the value if it is the only element found, or returns the default value for the type if either no elements are found, or multiple elements are found.

var numbers = new List<int>() { 7, 1, 9, 41, 8, 22 };
var singleNumber = numbers.SingleOrDefault(x => x < 2); //1
var multipleResult = numbers.SingleOrDefault(x => x < 10); //0
var noneResult = numbers.SingleOrDefault(x => x > 90); //0

The key thing these methods have in common is that, if the condition isn't matched by an element, they return the default value of the collection's type. For integers that is 0, for strings it is null, for classes it would also be null.

But what if we didn't want to return the default value for the type? What if, instead, we wanted to return a custom value when the condition is not satisfied?

New Implementation

In .NET 6, methods such as FirstOrDefault() and SingleOrDefault() have a new overload that allows us to specify a custom value to return if their conditions are not matched.

var numbers = new List<int>() { 7, 1, 9, 41, 8, 22 };

var matchingNumber = numbers.FirstOrDefault(x => x > 50, -1); //-1
var matchingNumber = numbers.SingleOrDefault(x => X > 30, -1); //41

This also works when the collections are empty:

var emptyCollection = new List<string>();

var firstName = emptyCollection.FirstOrDefault("None Found"); //None Found

Demo Project

As with all posts in this series, there is a demo project you can check out over on GitHub, which has more examples of how to use the new FirstOrDefault(), SingleOrDefault(), and LastOrDefault() method overloads. Check it out!

GitHub - exceptionnotfound/NET6BiteSizeDemos
Contribute to exceptionnotfound/NET6BiteSizeDemos development by creating an account on GitHub.

Happy Coding!