Udostępnij za pośrednictwem


Linq features to make smaller code

I have been working on some code that involves using Linq to query a database and came across something that I thought was really useful.  So here is the situation:

We have a query that we want to be able to sort in multiple ways.  This will allow the user to click on columns and sort by it.  That kind of thing.  The first way that I did this was to do something like the following:

 if (sortmethod.CompareTo("date") == 0)
{
    var c = from p in db.ProductSales
            from t in db.Products
           where (t.Id == p.ProductId)
           group t by t into g
           orderby g.Count() descending
           select g;
} else {
    var c = from p in db.ProductSales
            from t in db.Products
           where (t.Id == p.ProductId)
           group t by t into g
           orderby g.Key
           select g;
}

This can get very long if you have multiple things that someone can sort by.  So after doing some digging around, I found an alternative way that you can do this which is much shorter and much easier to follow:

 var c = from p in db.ProductSales
            from t in db.Products
            where (t.Id == p.ProductId)
            group t by t into g
            select g;

switch (sortmethod)
{
    case "date":
        c = c.OrderByDescending(g => g.Count());
        break;
    default:
        c = c.OrderBy(g => g.Key);
        break;
}

As you can see, this now allows us to just do the sorting based on what the user wants but the rest of the query doesn’t have to be redone.  This can save a lot of code and effort for development and testing.  Plus, you can imagine if there is a change to the database, in the first method, you would have to change the Linq query for each sort.  Where in the second method, you change it once and that is all.

Hope this is useful and happy coding.

Comments

  • Anonymous
    December 12, 2008
    I've seen this in a few blogs, I bet in 5 years someone will be blogging about this same technique

  • Anonymous
    December 14, 2008
    If you want to make it even more dynamic, you can go through the steps covered here: http://stackoverflow.com/questions/41244/dynamic-linq-orderby

  • Anonymous
    December 17, 2008
    This was the first time I saw this tip, so thanks.