Select List item with max value using LINQ query

前端 未结 3 1087
無奈伤痛
無奈伤痛 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:34

    The following should work:

    var mxKVALoad = loadRecords
                    .Where(l => l.totalLoadKva == loadRecords.Max(l => l.TotalLoadKva));
    

    Alternatively, you can use MaxBy from the MoreLINQ library

    0 讨论(0)
  • 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<TSource, TComp>(this IEnumerable<TSource> source, Func<TSource, TComp> 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.

    0 讨论(0)
  • 2021-01-26 13:01

    I don't think so you need to group them just for getting record with highest TotalLoadKva,you can just use OrderByDescending to sort them on the TotalLoadKva and then select the top first record using First or FirstOrDefault method:

    var maxKVALoad = loadRecords.OrderByDescending(l => l.TotalLoadKva).FirstOrDefault();
                     // will return the record with highest value of TotalLoadKva
    

    the preferred way will be to use FirstOrDefault() as First() will throw exception saying:

    The Sequence contains no elements

    If it is guarranted that there will always be rows returned then First() can be safe to use, otherwise use FirstOrDefault which will not throw exception if collection is empty.

    0 讨论(0)
提交回复
热议问题