设置匿名类型属性名称 [英] Setting anonymous type property name
本文介绍了设置匿名类型属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有以下代码:
string SomeConst = "OtherName";
var persons = GetPersons(); //returns list of Person
var q = persons.Select(p =>
new
{
SomeConst = p.Name
});
基本上我希望在 q 序列中具有该属性的匿名类型名为 OtherName 而不是 SomeConst.我怎样才能实现这种行为?
Basically I'd expect to have in q sequence of anonymous type with the property named OtherName and not SomeConst. How can I achieve such a behaviour?
推荐答案
你不能那样做.匿名类型的属性名称必须在编译时已知.为什么你需要这样做?
You can't do that. The names of the properties of an anonymous type must be known at compile time. Why exactly do you need to do that?
您可以通过创建字典序列而不是匿名对象来实现类似的效果:
You could achieve a similar effect by creating a sequence of dictionaries instead of anonymous objects:
string SomeConst = "OtherName";
var persons = GetPersons(); //returns list of Person
var q = persons.Select(p =>
new Dictionary<string, string>
{
{ SomeConst, p.Name }
});
这篇关于设置匿名类型属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文