IQueryable to List<T>

别说谁变了你拦得住时间么 提交于 2019-12-23 03:43:12

问题


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...


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5989983/iqueryable-to-listt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!