Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting anonymous type property name

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?

like image 443
user759141 Avatar asked May 18 '11 12:05

user759141


People also ask

How do you declare an anonymous type?

You create anonymous types by using the new operator together with an object initializer. For more information about object initializers, see Object and Collection Initializers. The following example shows an anonymous type that is initialized with two properties named Amount and Message .

Which of the following selects an anonymous type?

In LINQ, select clause generates anonymous type so that in a query you can include properties that are not defined in the class.

When can anonymous types be created?

We can create anonymous types by using “new” keyword together with the object initializer. As you can see from the below code sample, the type is store in a var and has two data items.


1 Answers

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 } }); 
like image 154
Thomas Levesque Avatar answered Sep 17 '22 13:09

Thomas Levesque