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?
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 .
In LINQ, select clause generates anonymous type so that in a query you can include properties that are not defined in the class.
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.
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 } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With