如何使匿名类型属性名称动态化?

如何使匿名类型属性名称动态化?

问题描述:

我有以下LinqToXml查询:

I have a following LinqToXml query:

  var linqDoc = XDocument.Parse(xml);
  var result = linqDoc.Descendants()
    .GroupBy(elem => elem.Name)
    .Select(group => new 
    { 
      TagName = group.Key.ToString(), 
      Values = group.Attributes("Id")
        .Select(attr => attr.Value).ToList() 
    });

是否有可能使我的匿名类型的字段成为变量值,从而使其成为(不起作用):

Is it possible somehow to make the field of my anonymous type it to be the variable value, so that it could be as (not working):

  var linqDoc = XDocument.Parse(xml);
  var result = linqDoc.Descendants()
   .GroupBy(elem => elem.Name)
   .Select(group => new 
   { 
     group.Key.ToString() = group.Attributes("Id")
       .Select(attr => attr.Value).ToList() 
   });

否,即使匿名类型也必须具有编译时字段名称.似乎想要一个不同类型的集合,每种类型都有不同的字段名称.也许您可以改用 Dictionary ?

No, even anonymous types must have compile-time field names. It seems like to want a collection of different types, each with different field names. Maybe you could use a Dictionary instead?

  var result = linqDoc.Descendants()
                      .GroupBy(elem => elem.Name)
                      .ToDictionary(
                                    g => g.Key.ToString(), 
                                    g => g.Attributes("Id").Select(attr => attr.Value).ToList()
                                   );

请注意,可以轻松地将Dictionary序列化为JSON:

Note that Dictionaries can be serialized to JSON easily:

{ 
  "key1": "type1":
            {
              "prop1a":"value1a",
              "prop1b":"value1b"
            }, 
  "key2": "type2":
            {
              "prop2a":"value2a",
              "prop2b":"value2b"
            }
}