简体   繁体   English

Linq FirstOrDefault - 一个班轮

[英]Linq FirstOrDefault - one liner

i have the following code to determine a age from a Person 我有以下代码来确定一个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. 我按ID选择一个Person ,如果它不存在,则默认值为20。

The 2nd line is invalid, because Age can't be null but Person can be. 第二行无效,因为Age不能为null但是Person可以。 Is there a way to get this working in one line ? 有没有办法让这个工作在一条线上 I've tried with DefaultIfEmpty but doesn't seem to work. 我尝试过使用DefaultIfEmpty,但似乎没有用。

You can use the overload of Enumerable.DefaultIfEmpty : 您可以使用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). 如您所见,不再需要FirstOrdefault ,因为如果输入序列为空(id-filter没有返回任何人), FirstOrdefault采用默认值。

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

Only in C# 6. 仅限于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. 无论如何,它并不漂亮,但你想尽可能地做到这一点,同时仍然计算几个潜在的NullPointerExceptions。 Please dont do this in a one liner, and please dont make the int nullable to acheive that. 请不要在一个内衬中执行此操作,并且请不要使用int nullable来实现这一点。 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. 请注意,我建议使用long if if语句以不同的方式执行它,以实现零代码重复和可读性。

Person person = ctx.Person.Where(x => x.Create > Date && x.ID.Equals("foo")).FirstOrDefault()

int age = (person != null) ? person.Age : 20;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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