简体   繁体   English

从实体动态选择属性列表

[英]Dynamically select a list of properties from an entity

I have a collection IEnumerable. 我有一个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. 在LINQ查询中,最好只从类型T中选择此集合中的属性,然后选择匿名类型,其中T是POCO业务对象。

Example: 例:

My IEnumerable contains properties "Name", "Age". 我的IEnumerable包含属性“名称”,“年龄”。

My POCO is: 我的POCO是:

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. 我想实现与以下相同的效果,但不对匿名类型的成员进行硬编码,而是使用我的PropertyInfo集合。

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. 如果使用的是Entity Framework,则可以将Entity SQL与动态构造的字符串where子句一起使用,但是尽管不是严格的硬编码,但我仍在使用属性的字符串名称。

Could I not perhaps dynamically construct an expression for the .Select projection method that determines which properties are included in the result object? 我是否可能无法为.Select投影方法动态构造一个表达式,该表达式确定结果对象中包含哪些属性?

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) 即使是匿名类型,编译器也需要静态知道枚举中的项目类型( var关键字表示隐式类型,而不是动态类型)

Why do you need to do that ? 为什么需要这样做? If you explain what your requirement is, we can probably suggest another way to do it 如果您解释您的要求是什么,我们可能会建议另一种方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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