开发者

Use dynamic "string alias" for new anonymous object's property in LINQ? [duplicate]

This question already has answers here: Dynamically set the property name of a C# anonymous type 开发者_运维问答 (6 answers) Closed 8 years ago.

I have a string variable, myFieldname. How can I use its value as a alias in a linq expression?

Collapse

string myFieldname = "theName";
var q = (from d in data select new { d.Id, myFieldname = d.Amount });

I want theName be the alias not the myFieldname itself.


You cannot (at least, not in any sane way). The only way I can see to do that would be to use an expando object, and then:

foreach(var pair in data select new { d.Id, d.Amount})
{
    var obj = new ExpandoObject();
    IDictionary<string, object> dict = obj;
    dict[myFieldname] = obj.Amount;
    dict["Id"] = d.Id;
    // add obj to a list or similar
}

You can use ExpandoObject with the dynamic API, but even then I'm unclear what this is meant to help you with...


You can't - easily anyway - because the anonymous type ends up as a real type within your code, including the property name.

You'd have to generate a type at execution time, and then create an expression tree for your projection. This sounds like a lot of work to me.

Why would you want the property name to be dynamic anyway? Why can't you just adjust the name that's used elsewhere dynamically? What's the bigger picture here?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜