LINQ Max() with Nulls

后端 未结 8 1689
自闭症患者
自闭症患者 2020-12-29 00:49

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

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

double max          


        
8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-29 01:47

    If you want to provide a default value for X of a null point:

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

    Or to provide a default for an empty list:

    int max = points.Where(p => p != null)
                    .Select(p => p.X)
                    .DefaultIfEmpty()
                    .Max();
    

提交回复
热议问题