LINQ query needs either ascending or descending in the same query

Posted by Sir Psycho on Stack Overflow See other posts from Stack Overflow or by Sir Psycho
Published on 2010-03-29T06:23:41Z Indexed on 2010/03/29 6:33 UTC
Read the original article Hit count: 270

Filed under:
|

Is there anyway this code can be refactored? The only difference is the order by part.

Idealy I'd like to use a delegate/lamda expression so the code is reusable but I don't know how to conditionally add and remove the query operators OrderBy and OrderByDescending

var linq = new NorthwindDataContext();

        var query1 = linq.Customers
            .Where(c => c.ContactName.StartsWith("a"))
            .SelectMany(cus=>cus.Orders)
            .OrderBy(ord => ord.OrderDate)
            .Select(ord => ord.CustomerID);

        var query2 = linq.Customers
            .Where(c => c.ContactName.StartsWith("a"))
            .SelectMany(cus => cus.Orders)
            .OrderByDescending(ord => ord.OrderDate)
            .Select(ord => ord.CustomerID);

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ