iloveseven
iloveseven

Reputation: 685

Change what is returned by the SingleOrDefault method

Is it possible to change what is returned by the SingleOrDefault method?

Or will the default be always null?

Upvotes: 1

Views: 66

Answers (2)

Fabio
Fabio

Reputation: 32445

You can by preceding .SingleOrDefault with .DefaultIfEmpty extension method

var numbers = new[] { 1, 2, 3, 4, 5 }
var result = numbers.Where(number => number > 10)
    .Select(number => $"Number: {number}")
    .DefaultIfEmpty("None")
    .SingleOrDefault();

Console.WriteLine(result); // None

Because we explicitly providing default value we can use Single method instead of SingleOrDefault

Upvotes: 2

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89361

Is it possible to change what is returned by the SingleOrDefault method in EF Core?

No. "Default" in this context means "Null except for non-nullable value types, then the default value". The terminology is borrowed from the default operator in C#.

You can, of course, provide your own Extension Method that does whatever you want. EG:

static class MyDefaultExtension
{
    public static T SingleOrDefault<T>(this IEnumerable<T> col, Func<T> defaultFactory)
    {
        using (var e = col.GetEnumerator())
        {
            if (e.MoveNext())
            {
                var rv =  e.Current;
                if (e.MoveNext())
                {
                    throw new InvalidOperationException("Sequence contains more than one element");
                }
                return rv;
            }
        }

        return defaultFactory();
    }
}

Upvotes: 3

Related Questions