简体   繁体   中英

Linq FirstOrDefault - one liner

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: 在此输入图像描述

你可以这样做:

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM