gpt4 book ai didi

c# - IEnumerable 到 T[] 数组

转载 作者:行者123 更新时间:2023-11-30 13:31:24 24 4
gpt4 key购买 nike

可能问题标题不正确。我有以下变量

IEnumerable x = // some IEnumerable
System.Type y = // some type

如何迭代 x 以生成包含类型 y 的项目的数组?

当我浏览互联网时,我发现:

public T[] PerformQuery<T>(IEnumerable q)
{
T[] array = q.Cast<T>().ToArray();
return array;
}

请注意,我无法调用该方法 PerformQuery 因为 y类型为 System.Type换句话说,称它为 PerformQuery<typeof(y)>(x);PerformQuery<y>(x);会给我一个编译器错误。


编辑

这就是我遇到这个问题的原因。我有网络服务,我向它发布两件事。我要查询的表类型(示例 typeof(Customer)),以及实际的字符串查询示例“Select * from customers”

    protected void Page_Load(object sender, EventArgs e)
{
// code to deserialize posted data
Type table = // implement that here
String query = // the query that was posted

// note DB is of type DbContext
IEnumerable q = Db.Database.SqlQuery(table, query );

// here I will like to cast q to an array of items of type table!

最佳答案

您可以使用表达式树:

public static class MyExtensions
{
public static Array ToArray(this IEnumerable source, Type type)
{
var param = Expression.Parameter(typeof(IEnumerable), "source");
var cast = Expression.Call(typeof(Enumerable), "Cast", new[] { type }, param);
var toArray = Expression.Call(typeof(Enumerable), "ToArray", new[] { type }, cast);
var lambda = Expression.Lambda<Func<IEnumerable, Array>>(toArray, param).Compile();

return lambda(source);
}
}

它生成 x => x.Cast<Type>().ToArray()给你,Type在运行时已知。

用法:

IEnumerable input = Enumerable.Repeat("test", 10);
Type type = typeof(string);

Array result = input.ToArray(type);

关于c# - IEnumerable 到 T[] 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21920278/

24 4 0