Dynamically select a list of properties from an entity
I have a collection IEnumerable. In a LINQ query, preferably, I would like to select only the properties in this collection from type T, into an anonymous type, where T is a POCO business object.
Example:
My IEnumerable contains properties "Name", "Age".
My POCO is:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
}
I want to achieve the same e开发者_运维技巧ffect as below, but without hard-coding the members of the anonymous type, and instead using my PropertyInfo collection.
IEnumerable<Person> peeps = GetPeople();
var names = from p in peeps
select new {Name = p.Name, Age = p.Age};
If I was using Entity Framework, I could use Entity SQL with a dynamically constructed string where
clause, but then although not strictly hard-code, I'm still using string names of the properties.
Could I not perhaps dynamically construct an expression for the .Select projection method that determines which properties are included in the result object?
You can't do that. The compiler needs to know statically the type of the items in the enumeration, even if it's an anonymous type (the var
keyword denotes implicit typing, not dynamic typing)
Why do you need to do that ? If you explain what your requirement is, we can probably suggest another way to do it
精彩评论