Q:

How to make an anonymous types property name dynamic?

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

A:

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"
            }
}

