4

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.

ekad
  • 14,436
  • 26
  • 44
  • 46
waldecir
  • 376
  • 2
  • 8
  • 21

1 Answers1

12

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @waldecir: It's not clear what you mean. Where would you want to use that? You could use it in the grouping, or in the classes you create... basically you need to learn the basics of LINQ to Objects, and it will provide you a *lot* of flexibility. – Jon Skeet Jun 14 '11 at 20:04