如何在List中获得最大Id,然后返回列表

时间:2013-05-15 13:23:59

标签: linq c#-4.0 group-by max

我有这样的结构:

No  ID  Name Status
1    1    A    1
2    1    B    1
3    1    c    1
4    1    D    1
5    2    E    3
6    2    F    3
7    2    G    3

当我获得列表结果时,我想运行一个linq获取每个状态和行详细信息的最大行。就像:

No  ID  Name Status
4    1    D    1
7    2    G    3

表示状态的最新条目。

有没有办法,因为我已经尝试了所有Max,Orderby降序但我得到单个结果但是我需要一个List作为结果。

1 个答案:

答案 0 :(得分:3)

您必须提取相同ID(GroupBy)的组,然后使用SelectMany导出每个组的最大值No:

public void Exec()
{
    var items = new List<Item>{ 
        new Item{ No = 1, Id = 1, Name = "A", Status = 1} ,
        new Item{ No = 2, Id = 1, Name = "B", Status = 1} ,
        new Item{ No = 3, Id = 1, Name = "C", Status = 1} ,
        new Item{ No = 4, Id = 1, Name = "D", Status = 1} ,
        new Item{ No = 5, Id = 2, Name = "E", Status = 1} ,
        new Item{ No = 6, Id = 2, Name = "F", Status = 1} ,
        new Item{ No = 7, Id = 2, Name = "G", Status = 1} ,

    };

    var result = items
                    .GroupBy(groupedItems => groupedItems.Id)
                    .SelectMany(i => items
                                         .Where(innerItem => innerItem.Id == i.Key && innerItem.No == i.Max(ii => ii.No))
                                         .Select(innerItem => innerItem)                                             
                                         );

    foreach (var item in result)
        Console.WriteLine("Max item of Id {0} : No = {1}, Name = {2}, Status = {3}", item.Id, item.No, item.Name, item.Status);


}

private class Item
{
    public Int32 No { get; set; }
    public Int32 Id { get; set; }
    public String Name { get; set; }
    public Int32 Status { get; set; }
}

输出:

Max item of Id 1 : No = 4, Name = D, Status = 1
Max item of Id 2 : No = 7, Name = G, Status = 1

替代:

items.GroupBy(groupedItems => groupedItems.Id)
     .Select(g => g.OrderByDescending(x => x.No).First())