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,
Posted
03-28-2008 9:09 PM
by
Derik Whittaker