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.

Published 12 December 08 09:50 by Tom
Filed under: ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Eber Irigoyen said on December 12, 2008 2:01 PM:

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

# John Sheehan said on December 14, 2008 8:35 PM:

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

# Martin N Jensen said on December 17, 2008 9:27 AM:

This was the first time I saw this tip, so thanks.

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required

Search

This Blog

Syndication

Page view tracker