IQueryable to List

2019-05-30 17:24发布

I know IQueryable yields no result but just an expression builder, my problem is how can actually use it to execute query and return the set as List to be able to bind it on a grid.

  IQueryable query = _campaignManager.GetCampaign(filter, values);

  // this line returns error
  List<Campaign> campaigns = query.Cast<Campaign>().ToList();

  grdCampaigns.DataSource = campaigns;
  grdCampaigns.DataBind();

additional details: GetCampaign()

    public IQueryable GetCampaign(string filter, params object[] values)
    {
        string parameters = string.Empty;
        foreach (object obj in values)
        {
            parameters += obj.ToString() + ",";
        }

        parameters.Remove(parameters.Count() - 1, 1);

        var query = context.Campaigns.Where(filter, parameters)
           .Select("new(CampaignID,CampaignName)");

        return query;
    }

I'm using DynamicQueryable for dynamic linq queries

The .Select Extension method of the DynamicQueryable

     public static IQueryable Select(this IQueryable source, string selector, params object[] values)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (selector == null) throw new ArgumentNullException("selector");
        LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, null, selector, values);
        return source.Provider.CreateQuery(
            Expression.Call(
                typeof(Queryable), "Select",
                new Type[] { source.ElementType, lambda.Body.Type },
                source.Expression, Expression.Quote(lambda)));
    }

IQueryable .Where() extension

       public static IQueryable Where(this IQueryable source, string predicate, params object[] values)
    {
        if (source == null) throw new ArgumentNullException("source");
        if (predicate == null) throw new ArgumentNullException("predicate");
        LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, typeof(bool), predicate, values);
        return source.Provider.CreateQuery(
            Expression.Call(
                typeof(Queryable), "Where",
                new Type[] { source.ElementType },
                source.Expression, Expression.Quote(lambda)));
    }

thanks...

2条回答
ゆ 、 Hurt°
2楼-- · 2019-05-30 17:58

IQueryable can be of type T e.g. IQueryable query=+CampaignManager.GetCampaign

but since you are using IQueryable you can use

var enumerator= c.GetEnumerator();
            while (enumerator.MoveNext())
            {
             //add these records to some collection say Collection or Campaign or Create any entity with Name and Id and then assign that collection to DataSource    
            }

i have tried that it's working you can proceed wit it.

查看更多
▲ chillily
3楼-- · 2019-05-30 18:07

With .NET 4.0 and a slight modification to the Dynamic library, we can achieve the expected result for: var campaigns = query.Cast<dynamic>().ToList(); or even var campaigns = query.ToList();


Here is how to do it:
Change:

public abstract class DynamicClass {

to:

public abstract class DynamicClass : System.Dynamic.DynamicObject {


Here is a working code using the modified library:

var query = db.Customers.Where("City == @0 and Orders.Count >= @1", "London", 10).
            OrderBy("CompanyName").
            Select("New(CompanyName as Name, Phone)");

foreach (var val in query.Cast<dynamic>().ToList())
     Console.WriteLine(string.Format("Name: {0}, Phone: {1}", val.Name, val.Phone));


We may also add an overloaded extension method to the DynamicQueryable class:

public static IQueryable<T> Select<T>(this IQueryable source, string selector, params object[] values)
{
    return Select(source, selector, values).Cast<T>();
}

Then we should be able to call like this:

var query = db.Customers.Where("City == @0 and Orders.Count >= @1", "London", 10).
            OrderBy("CompanyName").
            Select<dynamic>("New(CompanyName as Name, Phone)");

foreach (var val in query.ToList())
    Console.WriteLine(string.Format("Name: {0}, Phone: {1}", val.Name, val.Phone));


P.S: From MSDN:

Any object can be converted to dynamic type implicitly.

So we should be able to call Cast<dynamic>() without the proposed change.

查看更多
登录 后发表回答