Devlico.Us
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @devlicious

Derik Whittaker

Thoughts on Software Development, .Net, OOP, Design Patterns and all things cool



Sorting List's the .Net 3.5 Way

This post is another in the recent string of How-to's.  But it is just so hard to resist.  .Net 3.5 has so many cool features, it is just fun to explore them all.

Ok, so here is the issue we are going to solve today.  We have a list of entities and we need to sort them.  In this post I will show you 3 different ways to accomplish this task, all producing the same result, but using different techniques (hey Peter, go ahead and show me a 4th and better way :) ).

A little up front declarations.  Each method will use the same list, so to save space I will declare this now.

List userList = new List
    {
        new User {FirstName = "Andy", LastName = "Tayler"},
        new User {FirstName = "Opie", LastName = "Tayler"},
        new User {FirstName = "Bee", LastName = "Tayler"},
        new User {FirstName = "Barney", LastName = "Fife"},
        new User {FirstName = "Goomer", LastName = "Pile"}
};

Sort Method 1 -- Using the Sort with IComarer

public void Sort_OldSchool()
{
    userList.Sort(new UserCompare());
}

// Sort class
private class UserCompare : IComparer<User>
 {
    public int Compare( User x, User y )
    {
    return x.LastName.CompareTo( y.LastName );
}

The above works, but requires you to create a custom class that implements the IComparer<User> interface to do the trick.

Sort Method 2 -- Using Lambda and extension methods

[Test]
public void Sort_UsingLambda()
{
	userList = userList.OrderBy( user => user.LastName ).ToList();
}

This way works great, it is clean and very readable.

Sort Method 3 -- Use Linq2Objects

[Test]
public void Sort_UsingLinq()
{
	userList = ( from u in userList
        	orderby u.LastName, u.FirstName
                select u ).ToList();
}

By using Linq you open yourself up to a whole new level of flexibility. You can not only sort (OrderBy), you can filter, return only a select number of rows, etc, etc.  Basically you can do anything that Linq provides.

As you can see from the above, they all accomplish the same goal but method 2 & 3 are just more fun.  Besides, if you are going to be using .Net 3.5 you might as well use the new features.

BTW, all the methods (except 3 since it sorts by LastName and FirstName) above produce the following output.
Barney Fife
Goomer Pile
Andy Tayler
Opie Tayler
Bee Tayler

Till next time,



Comments

Dew Drop - March 30, 2008 | Alvin Ashcraft's Morning Dew said:

Pingback from  Dew Drop - March 30, 2008 | Alvin Ashcraft's Morning Dew

# March 30, 2008 5:05 PM

Ray Akkanson said:

How would you compare lambda to a traditional methods as far as performance on large list objects?

Ray Akkanson

# August 13, 2008 9:16 AM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add

About Derik Whittaker

Derik is a .Net Developer/Architect specializing in WinForms working out the northern suburbs of Chicago. He is also believer and advocate for Agile development including SCRUM, TDD, CI, etc.

When Derik is not writing code he can be found spending time with his wife and young son, climbing on his bouldering wall, watching sports (mostly baseball), and generally vegging out. Check out Devlicio.us!

Our Sponsors

Red-Gate!