Tuesday, March 2, 2010

LINQ secondary sort using extension method syntax

You have a list of objects that you want to sort using LINQ. You want to sort by a primary and secondary key from the fields (properties or members) of the object. How do you do this?

The answer is to do two sorts. The first by the secondary key and the second by the primary key. Here's a little test console app that you can run to verify.

class Widget
{
    public int First { get; set; }
    public int Second { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        List<Widget> widgets = new List<Widget>();
        widgets.Add(new Widget { First = 1, Second = 6 });
        widgets.Add(new Widget { First = 2, Second = 6 });
        widgets.Add(new Widget { First = 3, Second = 5 });
        widgets.Add(new Widget { First = 4, Second = 5 });
        widgets.Add(new Widget { First = 5, Second = 4 });
        widgets.Add(new Widget { First = 6, Second = 4 });

        var firstSort = widgets.
          OrderByDescending(a => a.First).
            OrderBy(a => a.Second);
        foreach (Widget widget in firstSort)
        {
            Console.WriteLine("First {0} Second {1}",
                widget.First, widget.Second);
        }

        Console.ReadLine();
    }
}

The results of this run are:

First 6 Second 4
First 5 Second 4
First 4 Second 5
First 3 Second 5
First 2 Second 6
First 1 Second 6
Hit return to continue...

So we initially reverse sort by the First property, this will be the secondary sort. We then sort by the Second property, this will be the primary sort.

3 comments:

  1. It's just been pointed out to me that I could use:
    .OrderByDescending(a => a.LastUpdated).ThenBy(a.LastName)
    The strange thing is that I've even used ThenBy() in the past so not sure why I didn't think of this at the time I wrote this post.

    ReplyDelete