4

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.

Mehrdad
  • 2,054
  • 3
  • 20
  • 34

2 Answers2

7

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

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
6

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?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • because I don't know the name till runtime, and because the result is set for ItemSource of grid it's important to be the dynamic name – Mehrdad Jul 09 '11 at 07:42
  • @Mehrdad: That really *shouldn't* be the case - how is the name being used within the grid? What would you have done before LINQ? Assuming it's just a matter of displaying the right header or something like that, I'm sure that can be done dynamically in a different way. It would really help if you'd give us more information about what you're trying to do and why you think you need it to be dynamic. – Jon Skeet Jul 09 '11 at 07:46