Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group a list using linq c#

The scenario I have is as follows:

I have the following data -

ID, Name, Type, Location, GroupID

1, samename, Rock, New York, 12
2, samename, Jazz, Sydney, 12
3, samename, Rock, Sydney, 12
4, samename, Jazz, New York, 12    
5, name3, Opera House, Sydney, 14
6, name3, Opera House, London, 14
7, name2, Emirates, London, 13

And I would like to output it flattened based on the GroupID like below

ID, Name, Place, Location, GroupID

1, samename, {Rock,Jazz}, {New York,Sydney}, 12
5, name3, Opera House, {Sydney,London}, 14
7, name2, Emirates, London, 13

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

I believe the answer is something to do with SelectMany - but I can't work out the syntax - I've tried a few different ways.

my attempted solution - without flattening..

var q3 = Data.Where(b=>b.GroupID != null).GroupBy(x=> new { x.GroupID }, (key, group) => new 
{ 
  GroupID = key.GroupID,  
  Result =  group.Select(g=> new 
                         {                            
                           Type = g.Type, 
                           Location = g.Location,                                                  
                         }).ToList()
});
like image 398
GMan Avatar asked Dec 29 '25 21:12

GMan


1 Answers

Try this:

var answer = data.GroupBy(x => x.GroupID).Select(x => new { 
     ID = x.Min(y => y.ID),
     Name = x.Select(y => y.Name).ToList(),
     Type = x.Select(y => y.Type).ToList(),
     Location = x.Select(y => y.Location).ToList(),
     GroupID = x.Key
}).ToList();
like image 88
Slava Utesinov Avatar answered Jan 01 '26 13:01

Slava Utesinov