Select List item with max value using LINQ query

前端 未结 3 1089
無奈伤痛
無奈伤痛 2021-01-26 12:01

I have List loadRecords where T type defines as follow

public class TransformerLoadRecord
{

    public double TotalLoadKva { get; set; }
    public double Total         


        
3条回答
  •  抹茶落季
    2021-01-26 12:59

    You need to sort (descending) the source list and take the first element:

    var elementWithMaxKVA = loadRecords.OrderByDescending(l => l.TotalLoadKva).FirstOrDefault();
    

    But this is not the fastest way, because OrderBy* will have to do more work than simply look up the max value.

    You could instead implement your own extension method like that:

    // error handling and argument checks ommitted for brevity
    public static TSource MaxBy(this IEnumerable source, Func selector) where TComp : IComparable
    {    
        using (var enumerator = source.GetEnumerator())
        {
            TSource max = default(TSource);
            TComp maxV = default(TComp);
            if (!enumerator.MoveNext()) return max; // or throw
    
            max = enumerator.Current;
            maxV = selector(max);
    
            while(enumerator.MoveNext())
            {
                TSource current = enumerator.Current;
                TComp currentV = selector(current);
                if (currentV.CompareTo(maxV) <= 0) continue;
                maxV = currentV;
                max = current;
            }
    
            return max;
        }
    }
    

    And use it like

    var elementWithMaxKVA = loadRecords.MaxBy(l => l.TotalLoadKva);
    

    I think the MoreLinq nuget package already contains such a MaxBy method.

提交回复
热议问题