views:

37

answers:

1

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?

A: 

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

Thomas Levesque
I'm exporting a collection of JobCard objects. The properties of each object to be included in a CSV representation of the object depend on the user role. At the moment I am just looping through a list of properties included for a role and usign reflection to get their values from each JobCard object. I only used 'var' as an example. Could I not perhaps use 'dynamic'? I know nothing about that though.
ProfK
dynamic wouldn't help in that case. I think reflection is your only option...
Thomas Levesque
@Thomas, please see my edit. I know I said "in a LINQ query", but just for interest, the limitation on the dynamic property set is platform dependent and can be achieved using Entity Framework.
ProfK