問題描述
我有以下 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 中的空值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!