开发者

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

开发者 https://www.devze.com 2023-03-12 17:51 出处:网络
How to create a \"complex\" object from a list of fields ex.: public class Lines { public string itemName;

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,开发者_JAVA百科 example object:

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

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号