我使用了这个答案的修改版本:How to dynamically create a class in C#?创建一个代表类型化类的动态对象。
public static object CreateNewObject(string[] columnNames)
{
var myType = CompileResultType(columnNames);
return Activator.CreateInstance(myType) as IQueryable;
}
然后在主应用程序中:
var obj = MyTypeBuilder.CreateNewObject(rs.ColumnNames);
我需要以某种方式将其转换为 IQueryable
所以我可以执行一些 Linq 调用,例如 .where()
, .select()
等等。当然,我目前无法做到这一点,因为我的应用程序不知道该对象中到底有什么,或者该对象是什么。
所以我需要的是:
var obj = MyTypeBuilder.CreateNewObject(rs.ColumnNames);
List<obj> aListICanFill = new List<obj>();
..
aListICanFill.where(x => x.Equals("")).take(3);
我盲目地尝试了不同的转换,甚至未能尝试迭代对象 - 现在我完全陷入困境。
有什么办法可以做到这一点吗?
http://msdn.microsoft.com/en-us/library/bb882637.aspx似乎是我应该捕获的东西。
我的对象是什么样的:
最佳答案
如果您可以使用 List
using System;
using System.Collections.Generic;
using System.Linq;
namespace DynamicListTest
{
internal class Program
{
private static void Main(string[] args)
{
var dynamicObjects = GetDynamicObjects().Cast<dynamic>().AsEnumerable();
var itemsToPrint = dynamicObjects
.Where(item => item.Age > 30);
foreach (var item in itemsToPrint)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
private static IQueryable GetDynamicObjects()
{
return new List<dynamic>()
{
new { Name = "A", Age = 10 },
new { Name = "B", Age = 20 },
new { Name = "C", Age = 30 },
new { Name = "D", Age = 40 },
new { Name = "E", Age = 50 },
}.AsQueryable();
}
}
}
这会打印
{ 姓名 = D,年龄 = 40 }
{ 姓名 = E,年龄 = 50 }
关于c# - 将对象转换为可查询对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26709829/