简体   繁体   中英

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 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM