Lists and generics are now used much more commonly than the ArrayLists of old and one important reason why is how easily they can be sorted. One of the easiest ways to sort a list is to use a technique that involves the System.Comparison Delegate.
Don't worry, you don't really need to know very much about delegates or even the System.Comparison delegate.
First thing you need to do is setup a function that returns an integer and accepts two parameters of the type in your list.
private static int SortPostsByTitle(Post post1, Post post2)
{
return post1.Title.CompareTo(post2.Title);
}
In the example above, we intend to take a Post object and then sort it by titles. Using the string.CompareTo function is a quick way to return either a 1, 0 or -1 depending on how post1.Title and post2.Title are related.
Secondly, in your code that contains the list, simply make use of this function as shown below.
private void CreatePostList()
{
List<Post> listOfPosts = Post.GetPostsByCategory(cat.Id);
listOfPosts.Sort(SortPostsByTitle);
//bind the list to whatever control you need
}
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5