设置匿名类型属性名称

发布于 2024-11-08 04:53:34 字数 318 浏览 4 评论 0原文

假设我有以下代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

离去的眼神 2024-11-15 04:53:34

你不能那样做。匿名类型的属性名称必须在编译时已知。到底为什么你需要这样做?

您可以通过创建一系列字典而不是匿名对象来实现类似的效果:

string SomeConst = "OtherName";
var persons = GetPersons(); //returns list of Person
var q = persons.Select(p => 
new Dictionary<string, string>
{
    { SomeConst, p.Name }
});

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 }
});
终止放荡 2024-11-15 04:53:34

我知道您可以动态添加在编译时名称未知的属性的唯一方法是 ExpandoObject :

var q = persons.Select(p => { dynamic obj = new ExpandoObject(); obj.Name = p.Name; return obj; });

但我真的没有看到做这样的事情有任何兴趣。这样做很可能是一个非常糟糕的设计/想法。毫无疑问,你会创建比你解决任何问题更尴尬、不可读和难以维护的代码......

The only way I'm aware of you can dynamically add properties whose name is unknown at compile time is the ExpandoObject :

var q = persons.Select(p => { dynamic obj = new ExpandoObject(); obj.Name = p.Name; return obj; });

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...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文