LINQ Max() with Nulls

后端 未结 8 1641
自闭症患者
自闭症患者 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

    Well, you could just filter them out:

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

    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)
    
    0 讨论(0)
  • 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();
    
    0 讨论(0)
提交回复
热议问题