Thursday, November 15, 2007

Sorting a Generic List of Custom Objects Simply

For a defect I was working on today, I just wanted to sort a list of users by username in a very simple fashion.

Google failed me. I wasn't able to find a good example of how to do this easily in VB.NET. As usual, most examples are full of noise, like this, this, this, or that.

So, once I figured out how to do it, I thought I should share it.

First, we create a function to handle our comparison.

Private Function UsernameComparer(ByVal x As User, ByVal y As User) As Integer
Return x.UserName.CompareTo(y.UserName)
End Function

Next, we use it.

myUserList.Sort(AddressOf UsernameComparer)

Now our user list is sorted by username.

In C# 2.0, using anonymous methods, it can even be done all at once:

myUserList.Sort(delegate(User x, User y) {
return x.UserName.CompareTo(y.UserName);
});

If you know of an even simpler way to do this, leave some comments and let us know!