How to make anonymous type property name dynamic?

I have the following LinqToXml request:

  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 to somehow make the field of my anonymous type the value of a variable so that it can be like (doesn't work):

  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() 
   });
+4
source share
1 answer

No, even anonymous types must have compile-time field names. It seems like a collection of different types is required, each with different field names. Maybe you could use Dictionaryinstead?

  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 easily serialized in JSON:

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

Source: https://habr.com/ru/post/1546004/


All Articles