Link to home
Start Free TrialLog in
Avatar of Evan Cutler
Evan CutlerFlag for United States of America

asked on

IQueryable expression output

ok,
I have this code:
 
start = 0;
        rp = 5;
        sortname = "Title";
        sortorder = "OrderBy";

        IQueryable<Advertisement> ads = (from ad in ct.Advertisements
                                        select ad).Skip(start).Take(rp);

        total = ads.Count();

        ParameterExpression AdParam = Expression.Parameter(typeof(Advertisement), "ad");
        MemberExpression Admbr = Expression.PropertyOrField(AdParam, sortname);
        LambdaExpression adLambda = Expression.Lambda(Admbr, AdParam);

        Type[] exprArgTypes = { ads.ElementType, adLambda.Body.Type };

        MethodCallExpression AdCall = Expression.Call(typeof(Queryable), sortorder, exprArgTypes, ads.Expression, adLambda);

        IQueryable orderedads = ads.Provider.CreateQuery(AdCall);

Open in new window


The code creates a really pretty SQL to be fired.

I need to fire the SQL so I can get a List<Advertisements> filled up, or to have ads requery so I can invoke foreach, and get my data out.

Right now, I have the IQueryable expression output.  what's next?
Thanks.
Avatar of jagrut_patel
jagrut_patel
Flag of India image

orderedads.ToList() will execute your query and return List<Advertisement>. The result can then be iterated with foreach.

List<Advertisement> adList = orderedads.ToList();
foreach(Advertisement ad in adList)
{
}
Avatar of Evan Cutler

ASKER

it gives me this error...
Am I missing something?

'System.Linq.IQueryable' does not contain a definition for 'ToList' and no extension method 'ToList' accepting a first argument of type 'System.Linq.IQueryable' could be found (are you missing a using directive or an assembly reference?)      
Avatar of Fernando Soto
Hi arcee123;

The IQueryable interface type doen't have a method ToList to use. Convert the IQueryable to a Enumerable and then apply the ToList  method, so try it like this:

List<Advertisement> adList = orderedads.AsEnumerable().ToList();
foreach(Advertisement ad in adList)
{

}

Fernando
 
gives me two errors now:

'System.Linq.IQueryable' does not contain a definition for 'AsEnumerable' and the best extension method overload 'System.Data.DataTableExtensions.AsEnumerable(System.Data.DataTable)' has some invalid arguments      c:\Users\Evan\Documents\Visual Studio 2010\WebSites\ResourceD\Scratchpad\Ads.ashx

and

Instance argument: cannot convert from 'System.Linq.IQueryable' to 'System.Data.DataTable'      c:\Users\Evan\Documents\Visual Studio 2010\WebSites\ResourceD\Scratchpad\Ads.ashx

This is hard...lol
ASKER CERTIFIED SOLUTION
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That worked.... :)

Thanks much.
Not a problem, glad I was able to help.