开发者

IQueryable and sorting

开发者 https://www.devze.com 2023-03-05 17:29 出处:网络
It seems like that after receiving an IQueryable, I am not able to modify the query to enable a sort. Here is the code snippet.

It seems like that after receiving an IQueryable, I am not able to modify the query to enable a sort. Here is the code snippet. I am under the impression that with IQueryable (as opposed开发者_开发百科 to do IEnumerable) I should be able to do what I am attempting.

using (oc1 = new NWEntities())
{
    string customerid = "ALFKI";
    var q = GetOrders((o) => o.CustomerID == customerid);

    q.OrderBy(o => o.ShipCity);   // DOES NOT WORK !!!!!!!!
    foreach (var x in q)
    {
        Console.WriteLine(string.Format("Order#:{0} City:{1} for Customer {2}",
                                    x.OrderID,
                                    x.ShipCity,
                                    customerid));
    }
}

// Returns IQueryable
IQueryable<Order> GetOrders(Expression<Func<Order, Boolean>> predicate)
{            
    return (oc1.Orders.Where(predicate));            
}

The output is somehow not sorted by City. Am I missing something obvious ? Thank you for your time.


You need to store the result of OrderBy in another variable. You sorted the list, and then silently dropped the result, and did your iteration on the original:

var q = GetOrders(...);

// notice I store in **q2**
var q2 = q.OrderBy(o => o.ShipCity);
foreach (var x in q2)
0

精彩评论

暂无评论...
验证码 换一张
取 消