Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ query needs either ascending or descending in the same query

Tags:

c#

linq

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

Idealy I'd like to use a delegate/lambda 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);
like image 257
Razor Avatar asked Mar 29 '10 06:03

Razor


3 Answers

You can create your own reusable extension method which will do this:

public static IOrderedQueryable<TSource> OrderBy<TSource, TKey>
    (this IQueryable<TSource> source,
     Expression<Func<TSource, TKey>> keySelector,
     bool ascending)
{
     return ascending ? source.OrderBy(keySelector)
          : source.OrderByDescending(keySelector);
}

and similarly for ThenBy:

public static IOrderedQueryable<TSource> ThenBy<TSource, TKey>
    (this IOrderedQueryable<TSource> source,
     Expression<Func<TSource, TKey>> keySelector,
     bool ascending)
{
     return ascending ? source.ThenBy(keySelector)
          : source.ThenByDescending(keySelector);
}
like image 133
Jon Skeet Avatar answered Sep 16 '22 21:09

Jon Skeet


You can split your query up into bits, and use control flow logic. LINQ to SQL will magically construct the correct query as if you had typed it all one line! The reason this works is that the query is not sent to the database until you request the data, but instead is stored as an expression.

var linq = new NorthwindDataContext();
var query = linq.Customers
    .Where(c => c.ContactName.StartsWith("a"))
    .SelectMany(cus=>cus.Orders);

IOrderedQueryable<Order> query2;
if (useAscending) {
    query2 = query.OrderBy(ord => ord.OrderDate);
} else {
    query2 = query.OrderByDescending(ord => ord.OrderDate);
}

var query3 = query2.Select(ord => ord.CustomerID);
like image 28
Mark Byers Avatar answered Sep 17 '22 21:09

Mark Byers


return from T in bk.anbarsabts
       where T.kalaname == str
       orderby T.date descending
       select new { T.date, T.kalaname, T.model, T.tedad };
like image 25
peyman Avatar answered Sep 18 '22 21:09

peyman