Tuesday, December 7, 2010

VB.NET Sort Comparer

I found myself needing to sort Generic List of custom objects, in this case a list of the last seen users on a website. I wanted to sort the list by Date Last Seen Descending. I am primarily a C# developer, so I knew how to do this with a Delegate method. But, I am using an older version of VB and Delegates are not available. So I headed over to StackOverflow and found this great question, How to Sort A System.Collection.Generic.List in VB.NET. After looking at this article I created the following code:

public class UserLastSeen
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime LastSeen { get; set;}
}


public class UserLastSeenSorter
{
public void GetSortedList()
{
List(Of UserLastSeen) userList = GetUserList()
userList.Sort(AddressOf UserLastSeenDescendingComparer)
}
private Function UserLastSeenDescendingComparer(ByVal user1 As UserLastSeen, _ ByVal user2 as UserLastSeen) As Integer
{
Return user2.LastSeen.CompareTo(user1.LastSeen)
}
}

This worked great and was very easy.

No comments: