gpt4 book ai didi

c# - 将 IEnumerable 转换为 IQueryable,其中 T 未知

转载 作者:太空狗 更新时间:2023-10-29 23:24:54 27 4
gpt4 key购买 nike

我有一个 BindingSource谁的DataSource (定义为对象)可以是任何类型的 IEnumerable运行时的类(例如 IList<Foo> )。我需要将其转换为 IQueryable<T>这样我就可以将它传递给通用扩展:

IOrderedQueryable<TEntity> OrderUsingSortExpression<TEntity>(this IQueryable<TEntity> source, string sortExpression) where TEntity : class

到目前为止我有这个:

string order = "Message ASC";
Type thetype = bsTotalBindingSource.DataSource.GetType().GetGenericArguments()[0];
IEnumerable<object> totalDataSource = ((IEnumerable<object>)(bsTotalBindingSource.DataSource));
//Blowing up on this next line with 'System.Linq.Queryable is not a GenericTypeDefinition. MakeGenericType may only be called on a type for which Type.IsGenericTypeDefinition is true.'
MethodInfo asQueryableMethod = typeof(Queryable).MakeGenericType(thetype).GetMethod("AsQueryable", BindingFlags.Static | BindingFlags.Public, null, new[] { typeof(IQueryable<>) }, null);
MethodInfo genericAsQueryableMethod = asQueryableMethod.MakeGenericMethod(thetype);
MethodInfo orderUsingSortExpressionMethod = GetType().GetMethod("OrderUsingSortExpression");
MethodInfo genericUsingSortExpressionMethod = orderUsingSortExpressionMethod.MakeGenericMethod(thetype);
bsTotalBindingSource.DataSource = genericUsingSortExpressionMethod.Invoke(this, new object[] { genericAsQueryableMethod.Invoke(totalDataSource, null), order });

如您所见,这里的最终目标是能够从 DataSource 获取某些内容,获取其 RuntimeType IEnumerable<T>其中 T可以是任何东西,然后调用AsQueryable<T>所以它可以传递给一个接受 IQueryable<T> 的函数.

编辑在四处寻找我正在寻找的具体方法之后,我对这个问题有了更深入的了解。现在看起来像这样:

string order = "Message ASC";
Type thetype = bsTotalBindingSource.DataSource.GetType().GetGenericArguments()[0];
//Returns the AsQueryable<> method I am looking for
MethodInfo asQueryableMethod = typeof(Queryable).MakeGenericType(thetype).GetMethods()[1];
MethodInfo genericAsQueryableMethod = asQueryableMethod.MakeGenericMethod(thetype);
MethodInfo orderUsingSortExpressionMethod = typeof(SortExtension)GetType().GetMethods()[0];
MethodInfo genericUsingSortExpressionMethod = orderUsingSortExpressionMethod.MakeGenericMethod(thetype);
bsTotalBindingSource.DataSource = genericUsingSortExpressionMethod.Invoke(this, new object[] { genericAsQueryableMethod
//blows up here with 'Object of type 'System.RuntimeType' cannot be converted to type 'System.Collections.Generic.IEnumerable`1[LogRecordDTO]'.'
.Invoke(bsTotalBindingSource.DataSource, new object[] {thetype}), order });

最佳答案

你说你想转换IEnumerable<T>IQueryable<T>其中 T 的类型未知。

private void Test<T>(IEnumerable<T> x)
{
var queryableX = x.AsQueryable();
}

注意:您需要是 using System.Linq .

关于c# - 将 IEnumerable<T> 转换为 IQueryable<T>,其中 T 未知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12109388/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com