如何使匿名类型属性名称动态化? [英] How to make an anonymous types property name dynamic?
本文介绍了如何使匿名类型属性名称动态化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下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"
}
}
这篇关于如何使匿名类型属性名称动态化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文