LINQ MAX()与空值 [英] LINQ Max() with Nulls

查看:431
本文介绍了LINQ MAX()与空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含了一堆点(用X和Y分量)的列表。

I have a list that contains a bunch of Points (with an X and Y component).

我想获得最大x对于列表中的所有点,像这样的:

I want to get the Max X for all points in the list, like this:

double max = pointList.Max(p=> p.X);



问题是,当我在列表中,而不是一个点一个空。什么将是解决这个问题的最好办法。

The problem is when I have a null in the list instead of a point. What would be the best way to get around this issue?

推荐答案

好了,你可以只筛选出来:

Well, you could just filter them out:

pointList.Where(p => p != null).Max(p => p.X)

在另一方面,如果你想 s到被视为尽管他们被分有X坐标 0 (或类似),你可以这样做:

On the other hand, if you want nulls to be treated as though they were points having X-coordinate 0 (or similar), you could do:

pointList.Max(p => p == null ? 0 : p.X)

待办事项注意,如果序列为空,这两种方法都将抛出。这其中的一个解决方法(如果需要的话)将是:

Do note that both techniques will throw if the sequence is empty. One workaround for this (if desirable) would be:

pointList.DefaultIfEmpty().Max(p => p == null ? 0 : p.X)

这篇关于LINQ MAX()与空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆