Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ statement optimization

Tags:

c#

linq

var person = People.SingleOrDefault(p => p.Name == parameter);
SelectedPerson = person ?? DefaultPerson

Could this be written in one statement? Measing can I provide the default element that SingleOrDefault returns?

I am looking for someting like this (the second argument is the default element I provide).

var person = People.SingleOrDefault(p => p.Name == parameter, DefaultPerson);

The solution should also work for value types (ints, doubles, enums, structs, ...).

like image 220
Wolfgang Ziegler Avatar asked Jun 12 '26 01:06

Wolfgang Ziegler


2 Answers

You can use DefaultIfEmpty():

var person = People.Where(p => p.Name == parameter).DefaultIfEmpty(DefaultPerson).Single();
like image 80
Kirill Bestemyanov Avatar answered Jun 14 '26 14:06

Kirill Bestemyanov


You can define an extension:

public static T SingleOrDefault<T>
    (this IEnumerable<T> list, T defaultValue) 
    where T : class
{
    return list.SingleOrDefault() ?? defaultValue;
}

and then call it with:

var person = People.SingleOrDefault(p => p.Name == parameter, DefaultPerson);
like image 27
NominSim Avatar answered Jun 14 '26 14:06

NominSim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!