Group to key-value pair where value is a list of elements that share the same key

waldecir picture waldecir · Jun 14, 2011 · Viewed 9.4k times · Source

How to create a "complex" object from a list of fields

ex.:

public class Lines {
  public string itemName;
  public string locationName;
  public string locationGeo;

}

List<Lines> lines = new List<Lines>(){
    new Lines() {itemName= "item1", locationName="someloc1", locationGeo="1.11, 1.11"},
    new Lines() {itemName= "item1", locationName="someloc2", locationGeo="1.12, 1.12"},
    new Lines() {itemName= "item1", locationName="someloc3", locationGeo="1.13, 1.13"},
    new Lines() {itemName= "item2", locationName="someloc4", locationGeo="1.14, 1.14"},
    new Lines() {itemName= "item2", locationName="someloc5", locationGeo="1.15, 1.15"}
}

Group to something like, example object:

public class exampleLines{
    public string itemName;
    public locations locs;
}

ps.: this class doesn't exist at all.

Answer

Jon Skeet picture Jon Skeet · Jun 14, 2011

So you want to group by itemName? Something like:

var query = lines.GroupBy(x => x.itemName)
      .Select(g => new { ItemName = g.Key,
                         Locations = g.Select(x => new { Name = x.locationName,
                                                         Geo = x.locationGeo })
                                      .ToList() })
      .ToList();

That's got two anonymous types in - once for the "container" class, and once for the "location" part.