简体   繁体   English

如何将IEnumerable(没有类型)转换为IQueryable <T>?

[英]How to turn an IEnumerable (without type) into an IQueryable<T>?

Having used LINQ quite a bit I am stumbling over a basic task today: 我使用LINQ了很多,我今天在基本任务上遇到了磕磕绊绊:

Having an IQueryable<T> out of an IEnumerable (without a type specified). IEnumerable获取IQueryable<T> (没有指定类型)。

Specifically I want to query over parameters of an SqlParameterCollection . 具体来说,我想查询SqlParameterCollection的参数。 This is deriving from IDataParameterCollection, IList, ICollection, IEnumerable as described here . 这是从IDataParameterCollection, IList, ICollection, IEnumerable派生的IDataParameterCollection, IList, ICollection, IEnumerable如此处所述 However, these are all without the type specified. 但是,这些都没有指定的类型。

Thus my question boils down to: How to use LINQ to query over an SqlParameterCollection? 因此,我的问题归结为: 如何使用LINQ查询SqlParameterCollection?

Here's what I have done (the compiler did not complain): 这就是我所做的(编译器没有抱怨):

IQueryable<SqlParameter> queryable = 
    sqlCommand.Parameters.AsQueryable().Cast<SqlParameter>();
    //throws ArgumentException "source is not IEnumerable<>"

Note: I have searched quite a bit, but everyone is talking about IEnumerable<T> which is fairly easy to query using AsQueryable() of course. 注意:我已经搜索了很多,但每个人都在讨论IEnumerable<T> ,当然使用AsQueryable()查询相当容易。

I am interested in the reason why you want to do this. 我对你想要这样做的原因感兴趣。 This should do what you explained: 这应该做你解释的:

public IQueryable<T> AsQueryable<T>(IEnumerable list)
{
    return list.Cast<T>().AsQueryable();   
}

Call like this: 像这样打电话:

IQueryable<SqlParameter> query = AsQueryable<SqlParameter>(sqlParameterCollection);

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

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