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 effect 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.
ADDED: Could I not perhaps dynamically construct an expression for the .Select projection method that determines which properties are included in the result object?