如何获取Property ID 3?有一种方法可以将结果转换为Conta?
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.Where(c => c.Saldo == contas.Max(l => l.Saldo)) ;
答案 0 :(得分:1)
如果您只想要一个结果,请使用Single()
或First()
:
var result = contas.FirstOrDefault(c => c.Saldo == contas.Max(l => l.Saldo));
这将返回具有最大Saldo的Conta
对象。
答案 1 :(得分:1)
您需要MaxBy()
扩展方法。 Kodein
一旦你有了,解决方案变得简单:
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()的示例实现(Jon Skeet等人对此有所贡献):
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;
}
}
}
答案 2 :(得分:0)
var max = Users.OrderByDescending(x => x.Saldo).FirstOrDefault();
答案 3 :(得分:0)
而不是使用.Where()
使用Single()
/ SingleOrDefault()
/ First()
/ FirstOrDefault()
Single
将抛出异常。
SingleOrDefault
将抛出异常。
First
将抛出
FirstOrDefault
将抛出。