Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq FirstOrDefault - one liner

Tags:

c#

linq

c#-4.0

i have the following code to determine a age from a Person

var pList = ctx.Person.Where(x => x.Create > Date);
int Age = pList.Where(x => x.ID == "foo").FirstOrDefault().Age ?? 20;

I pick a Person by ID, if it doesn't exist the default value is 20.

The 2nd line is invalid, because Age can't be null but Person can be. Is there a way to get this working in one line? I've tried with DefaultIfEmpty but doesn't seem to work.

like image 518
Byyo Avatar asked Nov 28 '22 20:11

Byyo


2 Answers

You can use the overload of Enumerable.DefaultIfEmpty:

int Age = pList
    .Where(x => x.ID == "foo")
    .Select(x => x.Age)
    .DefaultIfEmpty(20)
    .First();

As you can see, FirstOrdefault is not necessary anymore since the default value is taken if the input sequence is empty(the id-filter returned no persons).

like image 162
Tim Schmelter Avatar answered Nov 30 '22 10:11

Tim Schmelter


int Age = pList.Where(x => x.ID == "foo").FirstOrDefault()?.Age ?? 20;

Only in C# 6.

For those in suspicion: enter image description here

like image 32
Ghasan غسان Avatar answered Nov 30 '22 09:11

Ghasan غسان