开发者

Linq select distinct values with comparison

开发者 https://www.devze.com 2023-02-28 22:19 出处:网络
I have a list of objects. E.g. List<coin> where they contain a string(denom) and int(year). If the list contains:

I have a list of objects. E.g. List<coin> where they contain a string(denom) and int(year). If the list contains:

"Quarter", 1954
"Quarter", 1990
"Penny", 1925  
"Nickel", 1900 
"Nickel", 2000

How can I get a result开发者_运维问答ant list where it contains the unique values with just the most recent year? E.g.:

"Quarter", 1990
"Penny", 1925
"Nickel", 2000


You can do this by grouping by name, then either ordering and taking the first result, or by using something like MaxBy from MoreLINQ:

var query = coins.GroupBy(x => x.Name)
                 .Select(g => g.MaxBy(x => x.Year));

or

var query = coins.GroupBy(x => x.Name)
                 .Select(g => g.OrderByDescending(x => x.Year).First());


You can do this using group by like:

 var query = from coin in myList
        group coin by coin.Name into grouped
        select new
        {
            Name = grouped.Key
            Year = grouped.Max(x => x.Year) 
        };

For another sample like this, check out "max - grouped" in the 101 Linq examples: 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)
    };
0

精彩评论

暂无评论...
验证码 换一张
取 消