设置匿名类型属性名称
假设我有以下代码:
string SomeConst = "OtherName";
var persons = GetPersons(); //returns list of Person
var q = persons.Select(p =>
new
{
SomeConst = p.Name
});
基本上我希望在 q 序列中具有具有属性的匿名类型 名为 OtherName 而不是 SomeConst。 我怎样才能实现这样的行为?
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
});
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能那样做。匿名类型的属性名称必须在编译时已知。到底为什么你需要这样做?
您可以通过创建一系列字典而不是匿名对象来实现类似的效果:
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:
我知道您可以动态添加在编译时名称未知的属性的唯一方法是 ExpandoObject :
但我真的没有看到做这样的事情有任何兴趣。这样做很可能是一个非常糟糕的设计/想法。毫无疑问,你会创建比你解决任何问题更尴尬、不可读和难以维护的代码......
The only way I'm aware of you can dynamically add properties whose name is unknown at compile time is the ExpandoObject :
But I really don't see any interest in doing such a thing. It is most probably a very bad design/idea to do so. You will undoubtly create more awkward, unreadable and unmaintenable code than you will solve anything...