How to make an anonymous types property name dynamic?

不问归期 提交于 2021-02-05 05:21:16

问题


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

回答1:


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

Note that Dictionaries can be serialized to JSON easily:

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


来源:https://stackoverflow.com/questions/24411916/how-to-make-an-anonymous-types-property-name-dynamic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!