我有一个对象列表。例如List<coin>
,其中它们包含字符串(dom)和int(year)。如果列表包含:
"Quarter", 1954
"Quarter", 1990
"Penny", 1925
"Nickel", 1900
"Nickel", 2000
我怎样才能得到一个结果列表,其中包含最近一年的唯一值?例如:
"Quarter", 1990
"Penny", 1925
"Nickel", 2000
您可以通过按名称分组,然后排序并获取第一个结果,或者使用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());
您可以使用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
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)
};