38

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?

Adriano Carneiro
  • 57,693
  • 12
  • 90
  • 123
user759141
  • 577
  • 1
  • 6
  • 11

2 Answers2

32

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 }
});
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • Say, the property name is to be extracted from a constant variable stored in some dictionary or even outside it. If the variable is constant isn't its value known at the compile time? – user759141 May 18 '11 at 12:20
  • 2
    There's not such thing as a "constant variable"... If it's a constant, you can use the actual name directly when you create the anonymous object. If it's a variable, it's not possible, but you can do it with a dictionary as explained in my answer – Thomas Levesque May 18 '11 at 12:22
  • So if I change the first line to const string SomeConst – user759141 May 18 '11 at 12:24
  • But WHY do you need to declare the property name as a constant? – Thomas Levesque May 18 '11 at 12:59
  • 1
    Because I'm using this value elsewhere and wanted to avoid typing same string value in a thousand different places; therefore i just declared the variable to hold the value and one of the usages is as a property name in an anonymous type. apparently the framework doesn't allow for such a usage so I'll stick with other approach. Thanks for the patience – user759141 May 18 '11 at 13:24
  • 9
    If you're using the same anonymous type in multiple places, you should create a named type – Thomas Levesque May 18 '11 at 13:52
0

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

Ssithra
  • 710
  • 3
  • 8
  • this give me syntax error:"lambda expression with a statement body cannot be converted to an expression tree" – Alaa Jabre Jan 23 '15 at 07:09