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.
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).
int Age = pList.Where(x => x.ID == "foo").FirstOrDefault()?.Age ?? 20;
Only in C# 6.
For those in suspicion:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With