本文介绍了设置匿名类型的属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们说我有下面这段代码:
Let's say I have the following piece of code:
string SomeConst = "OtherName"; var persons = GetPersons(); //returns list of Person var q = persons.Select(p => new { SomeConst = p.Name });
基本上,我期望在问:匿名类型与序列命名属性 中文别名而非 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 } });更多推荐
设置匿名类型的属性名称
发布评论