Reputation: 2243
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.
Upvotes: 4
Views: 1166
Reputation: 5857
int Age = pList.Where(x => x.ID == "foo").FirstOrDefault()?.Age ?? 20;
Only in C# 6.
Upvotes: 5
Reputation: 2168
It's not pretty, by any means, but you wanted to do it as short as possible, while still counting for several potential NullPointerExceptions. Please dont do this in a one liner, and please dont make the int nullable to acheive that. The code below is not pretty, and not tested as i don't have the possibility at the moment.
Note that i would recommend doing it differently, with the long hand if statements, for zero code repetition and readability.
Person person = ctx.Person.Where(x => x.Create > Date && x.ID.Equals("foo")).FirstOrDefault()
int age = (person != null) ? person.Age : 20;
Upvotes: 1
Reputation: 460068
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).
Upvotes: 16
Reputation: 35780
You can do it like this:
int Age = pList.Where(x => x.ID == "foo").Select(x=>(int?)x.Age).FirstOrDefault() ?? 20;
Upvotes: 4