-1

There is First() which assumes there's an element, and FirstOrDefault() which defaults to the type's default. What about FirstOr(myDefault) where we want to provide our custom default value?

pete
  • 1,878
  • 2
  • 23
  • 43
  • 5
    Starting from .NET 6, you can specify a default value in `FirstOrDefault`: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.firstordefault – Klaus Gütter May 19 '23 at 04:11

1 Answers1

3

There is no such method but you can certainly implement your own. To do that, you would call FirstOrDefault and then check whether it returns null and use your own value instead. You can do that like this:

var value = list.FirstOrDefault() ?? yourDefault;

You can encapsulate that in your own extension method like so:

public static class EnumerableExtensions
{
    public static T FirstOrDefault<T>(this IEnumerable<T> source, T defaultValue)
    {
        return source.FirstOrDefault() ?? defaultValue;
    }
}

You can obviously do similarly for other overloads.

jmcilhinney
  • 50,448
  • 5
  • 26
  • 46