LINQ to SQL - Why can't you use a WHERE after an ORDER BY?

Posted by MCS on Stack Overflow See other posts from Stack Overflow or by MCS
Published on 2010-06-08T16:40:01Z Indexed on 2010/06/08 16:52 UTC
Read the original article Hit count: 283

Filed under:
|
|

The following code:

// select all orders
var orders = from o in FoodOrders
             where o.STATUS = 1
             order by o.ORDER_DATE descending
             select o;

// if customer id is specified, only select orders from specific customer
if (customerID!=null)
{
    orders = orders.Where(o => customerID.Equals(o.CUSTOMER_ID));
}

gives me the following error:

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Linq.IOrderedQueryable'. An explicit conversion exists (are you missing a cast?)

I fixed the error by doing the sorting at the end:

// select all orders
var orders = from o in FoodOrders
             where o.STATUS = 1
             select o;

// if customer id is specified, only select orders from specific customer
if (customerID!=null)
{
    orders = orders.Where(o => customerID.Equals(o.CUSTOMER_ID));
}

// I'm forced to do the ordering here
orders = orders.OrderBy(o => o.ORDER_DATE).Reverse();

But I'm wondering why is this limitation in place? What's the reason the API was designed in such a way that you can't add a where constraint after using an order by operator?

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ