问题描述
我有以下 Linq 查询:
I have the following Linq query:
result.Partials.Where(o => o.IsPositive).Min(o => o.Result)
当 result.Partials.Where(o => o.IsPositive)
不包含元素时,我得到一个异常.除了将操作一分为二并检查是否为空之外,是否有一种优雅的方法来处理这个问题?我有一堂课充满了这样的操作.
I get an exception when result.Partials.Where(o => o.IsPositive)
does not contains elements. Is there an elegant way to handle this other than splitting the operation in two and checking for null? I have a class full of operations like this one.
问题与 LINQ to Objects 相关.
The question is related with LINQ to Objects.
这是我得到的异常(翻译它说:序列为空):
This is the Exception I'm getting (translated it says: The sequence is empty):
推荐答案
Min
计算的简短总结- 无中介(例外!)
var min = result.Partials.Where(o => o.IsPositive).Min(o => o.Result);
这是您的情况:如果没有匹配的元素,则 Min
调用将引发异常 (InvalidOperationException
).
This is your case: if there are no matching elements, then the Min
call will raise an exception (InvalidOperationException
).
var min = result.Partials.Where(o => o.IsPositive)
.Select(o => o.Result)
.DefaultIfEmpty()
.Min();
DefaultIfEmpty
将在 0 元素上创建一个枚举,当列表中没有元素时.你怎么知道 0 是 Min
还是 0 代表没有元素的列表?
DefaultIfEmpty
will create an enumeration over the 0 element, when there are no elements in the list. How do you know that 0 is the Min
or if 0 stands for a list with no elements?
var min = result.Partials.Where(o => o.IsPositive)
.Min(o => (decimal?)o.Result);
这里的 Min
要么是 null(因为它等于 default(decimal?)
)要么是找到的实际 Min
.
Here Min
is either null (because that's equal to default(decimal?)
) or the actual Min
found.
所以这个结果的消费者会知道:
So a consumer of this result will know that:
- 当结果为
null
时,列表 没有元素 - 当结果是十进制值时,列表有一些元素,这些元素的
Min
就是返回值.
- When result is
null
then the list had no elements - When the result is a decimal value then the list had some elements and the
Min
of those elements is that returned value.
但是,如果这无关紧要,则可以调用 min.GetValueOrDefault(0)
.
However, when this doesn't matter, then min.GetValueOrDefault(0)
can be called.
这篇关于使用 Min 或 Max 时如何处理 LINQ 中的空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!