你想要一個MaxBy()
擴展方法。 These are widely available on NuGet。
一旦你的,該解決方案變得簡單:
List<Conta> contas = new List<Conta>();
contas.Add(new Conta { ID = 1, Saldo = 30 });
contas.Add(new Conta { ID = 2, Saldo = 50 });
contas.Add(new Conta { ID = 3, Saldo = 100 });
var result = contas.MaxBy(x => x.Saldo);
Console.WriteLine(result.ID);
這裏的MaxBy()的樣本實現(學分喬恩斯基特等人此):
public static class EnumerableExt
{
public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector)
{
return source.MaxBy(selector, Comparer<TKey>.Default);
}
public static TSource MaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector, IComparer<TKey> comparer)
{
using (IEnumerator<TSource> sourceIterator = source.GetEnumerator())
{
if (!sourceIterator.MoveNext())
{
throw new InvalidOperationException("Sequence was empty");
}
TSource max = sourceIterator.Current;
TKey maxKey = selector(max);
while (sourceIterator.MoveNext())
{
TSource candidate = sourceIterator.Current;
TKey candidateProjected = selector(candidate);
if (comparer.Compare(candidateProjected, maxKey) > 0)
{
max = candidate;
maxKey = candidateProjected;
}
}
return max;
}
}
}
的可能的複製[更好的方式返回一個對象由MAX()在LINQ](http://stackoverflow.com/questions/18766517/better-way-to-return-an-object-by-max-in-linq) – AndyJ
這將要是O(N^2)......至少可以在「Where()」之外獲取最大值 –