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?
精彩评论