C# LINQ - FirstOrDefault() 然后 Select()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15536830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:06:08  来源:igfitidea点击:

LINQ - FirstOrDefault() then Select()

c#linq

提问by Simon

I have the following LINQ query that fires and exception when the FirstOrDefault()returns null. Ideally I would like to avoid the null check. Is there a way to do this? I wish to return 0if there are no CPOffsetsthat satisfy the FirstOrDefault()call.

我有以下 LINQ 查询,当FirstOrDefault()返回空值时会触发和异常。理想情况下,我想避免空检查。有没有办法做到这一点?0如果没有CPOffsets满足FirstOrDefault()要求,我希望返回。

double offset = OrderedOffsets.FirstOrDefault(o => o.OffsetDateTime > cpTime).CPOffset;

The only way I can see to achieve this is the following:

我可以看到实现这一目标的唯一方法如下:

CPOffset cpOffset = OrderedOffsets.FirstOrDefault(o => o.OffsetDateTime > cpTime);
double offset = cpOffset != null ? cpOffset.CPOffset : 0;

Is there another more succinct way? Using Select()after the FirstorDefault()doesn't compile but I thought might be appropriate here?

还有其他更简洁的方法吗?Select()FirstorDefault()不编译后使用,但我认为在这里可能合适?

采纳答案by NSGaga-mostly-inactive

I think this should work, I'm not near by VS to check it out...

我认为这应该有效,我不在 VS 附近检查一下...

OrderedOffsets.Where(o => o.OffsetDateTime > cpTime).Select(x => x.CPOffset).FirstOrDefault();

回答by Servy

DefaultIfEmptycan be used to ensure that the collection always has at least one element.

DefaultIfEmpty可用于确保集合始终至少有一个元素。

double offset = OrderedOffsets.Where(o => o.OffsetDateTime > cpTime)
    .Select(o => o.CPOffset)
    .DefaultIfEmpty()
    .First();

回答by Romain

I think a good pattern could be :

我认为一个好的模式可能是:

double offset = (OrderedOffsets.FirstOrDefault(o => o.OffsetDateTime > cpTime) ?? someDefaultObject).CPOffset;

with someDefaultObjectan object holding default values... With this pattern, you can change easily you default values through your code !

使用someDefaultObject保存默认值的对象...使用此模式,您可以通过代码轻松更改默认值!

If OrderedOffsets can be a struct you could also just put your default value there ! :)

如果 OrderedOffsets 可以是一个结构,您也可以将默认值放在那里!:)