问题描述
我有以下Linq查询:
I have the following Linq query:
result.Partials.Where(o => o.IsPositive).Min(o => o.Result)
当result.Partials.Where(o => o.IsPositive)不包含元素时,出现异常.除了将操作分为两部分并检查是否为null之外,是否有一种优雅的方式来处理此问题?我有一堂课,像这样的操作.
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计算的简短摘要
A short summary of the calculation of a 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 0 stands for a list with no elements?
var min = result.Partials.Where(o => o.IsPositive)
.Min(o => (decimal?)o.Result);
此处的min为空(defaul(decimal?)
)或找到的实际Min.因此,此结果的使用者将知道,如果结果为null,则列表中没有元素;当结果为十进制值时,则列表中包含一些元素,而这些元素的Min为该值.
Here min is either null (defaul(decimal?)
) or the actual Min found. So a consumer of this result will know that if the result is null then the list had no elements and when the result is a value of decimal, then the list had some elements and the Min of those elements is that value.
但是,当这无关紧要时,可以调用min.GetValueOrDefault(0)
.
However, when this doesn't matter, then min.GetValueOrDefault(0)
can be called.
这篇关于使用Min或Max时如何处理LINQ中的空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!