Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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.

like image 437
Mehrdad Avatar asked Dec 13 '22 11:12

Mehrdad


2 Answers

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

like image 111
Marc Gravell Avatar answered Apr 19 '23 23:04

Marc Gravell


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?

like image 30
Jon Skeet Avatar answered Apr 20 '23 00:04

Jon Skeet