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