我有一个对象列表。例如。 List<coin>
其中包含字符串(denom)和int(year)。
如果列表包含:
"Quarter", 1954
"Quarter", 1990
"Penny", 1925
"Nickel", 1900
"Nickel", 2000
如何获得一个结果列表,其中包含最近一年的唯一值? E.g:
"Quarter", 1990
"Penny", 1925
"Nickel", 2000
答案 0 :(得分:7)
您可以按名称分组,然后排序并获取第一个结果,或使用MoreLINQ中的MaxBy
之类的内容来执行此操作:
var query = coins.GroupBy(x => x.Name)
.Select(g => g.MaxBy(x => x.Year));
或
var query = coins.GroupBy(x => x.Name)
.Select(g => g.OrderByDescending(x => x.Year).First());
答案 1 :(得分:3)
您可以使用group by
执行此操作,如:
var query = from coin in myList
group coin by coin.Name into grouped
select new
{
Name = grouped.Key
Year = grouped.Max(x => x.Year)
};
对于这样的另一个示例,请查看101 Linq示例中的“max - grouped”:http://msdn.microsoft.com/en-us/vcsharp/aa336747#maxGrouped
答案 2 :(得分:1)
var coins = new Coin[] { ... };
var recentCoins =
from coin in coins
group coin by coin.Denom into g
select new
{
Denom = g.Key,
MostRecentYear = g.Max(c => c.Year)
};