使用 Min 或 Max 时如何处理 LINQ 中的空值?
- 作者: 烟雨鹰城
- 来源: 51数据库
- 2022-10-21
问题描述
我有以下 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.
- C#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
