为 Linq Select 语句创建匿名对象

Skn*_*cht 6 c# linq

我得到一个字符串数组,其中包含属性名称。我只想在获取数据时加载这些属性,在本例中是通过实体框架从数据库获取数据。就像是:

\n\n
var result = db.myTable\n               .Where(x => x.Id == \xe2\x80\x9dsomeValue\xe2\x80\x9d)\n               .Select(y => new {y.someProperty, y.someOtherproperty, ...});\n
Run Code Online (Sandbox Code Playgroud)\n\n

如何从字符串数组创建匿名对象。我想要这样的东西:

\n\n
var MyObj = new {};\nforeach(var I in MyStrinArr)\n{\n   ... Add the properties here ...\n}\nvar result = db.myTable.Where(x => x.Id==\xe2\x80\x9dsomeValue\xe2\x80\x9d).Select(y => obj);\n
Run Code Online (Sandbox Code Playgroud)\n

Jer*_*gen 3

这(直接)不可能,因为匿名类是在编译时生成的。迭代字符串数组是在运行时进行的。所以这个没有可比性。


动态 linq 有多种可能性,您应该阅读 ScottGu 的博客:dynamic-linq它使用在运行时创建具有属性的类型的技术。下载dynamiclinqcsharp文件并检查源。ClassFactoryDynamicLibrary.cs 中有一个允许您创建类型的库。public Type GetDynamicClass(IEnumerable<DynamicProperty> properties)