Marcel
Marcel

Reputation: 15722

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:

Having an IQueryable<T> out of an IEnumerable (without a type specified).

Specifically I want to query over parameters of an SqlParameterCollection. This is deriving from IDataParameterCollection, IList, ICollection, IEnumerable as described here. However, these are all without the type specified.

Thus my question boils down to: How to use LINQ to query over an 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.

Upvotes: 4

Views: 1823

Answers (1)

Robert Fricke
Robert Fricke

Reputation: 3643

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);

Upvotes: 5

Related Questions