How to handle nulls in LINQ when using Min or Max?(使用 Min 或 Max 时如何处理 LINQ 中的空值?)
问题描述
我有以下 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
nullthen the list had no elements - When the result is a decimal value then the list had some elements and the
Minof 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 中的空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Min 或 Max 时如何处理 LINQ 中的空值?
基础教程推荐
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
