I have List loadRecords where T type defines as follow
public class TransformerLoadRecord
{
public double TotalLoadKva { get; set; }
public double Total
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.