简体   繁体   中英

How do I group a list using Linq

The scenario I have is as follows:

I have the following data -

ID, Name, Place, Location, GroupID

1, samename, Grand Central, New York, 12
2, samename, Opera House, Sydney, 12
3, samename, Opera House, Sydney, 12
4, name2, Emirates, London, 13
5, name3, Opera House, Sydney, 14

And I would like to output it as two tables

GroupID,Name

12, samename
13, name2
14, name3

GroupID, Place, Location

Grand Central, New York, 12
Opera House, Sydney, 12
Opera House, Sydney, 12
Emirates, London, 13
Opera House, Sydney, 14

This was really bad design that I have inherited - and I am trying to make it better.. without breaking the old code.

You need to do it in two steps, first group them on Name and GroupID :

var result = list.GroupBy(x=>new {x.GroupID, x.Name})
                 .Select(g=> new { GroupID = g.Key.GroupID, Name = g.Key.Name});

and in second case group them with other three columns ( GroupID , Place and Location ):

var result = list.GroupBy(x=>new {x.GroupID, x.Location,x.Place})
                 .Select(g=> new 
                         { 
                           GroupID = g.Key.GroupID, 
                           Location = g.Key.Location, 
                           Place = x.Key.Place
                         });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM