GMan
GMan

Reputation: 464

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.

Upvotes: 0

Views: 91

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

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

Upvotes: 4

Related Questions