How to get maximum Id in List and then return list

好久不见. 提交于 2020-01-06 07:44:35

问题


I have a structure like this:

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

I want to run a linq when I get a list results get maximum row where for each status and row details as well.Like:

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

Means latest entry for the status.

Is there a way around, as I have tried all Max, Orderby descending but I get single result but I need a List as a result.


回答1:


You have to extract the groups of a same id (GroupBy), and then export the max No for each group, with a SelectMany :

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; }
}

output :

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

Alternative:

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


来源:https://stackoverflow.com/questions/16566244/how-to-get-maximum-id-in-list-and-then-return-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!