We pay for user submitted tutorials and articles that we publish. Anyone can send in a contributionLearn More
In my previous article I talked about why SortedList is not a good option to use if you need a sorted collection with keys that are not unique. Today I will show you how to use a regular generic List<T> to store sorted items. You basically have 2 options.
this means that you will have to make your stored class Implement the IComparable Interface. Here is an example:
The implementation of IComparable is similar to the StringCompare one. if equal return 0, if bigger then return 1 and if smaller then return -1. Which helps us get rid of the If, Else and implement it like this:
the program from the last post will look like this:
And the output will be sorted after calling to List.Sort() on line 13. This way no matter how complicated you class is you can implement the comparison yourself and get the results you want.
A Comparer is a class that derives from Comparer<T> abstract class and has one method to override "int Compare(T1,T2)". For this example we will use the same dataclass but we will not implement the IComparable Interface. Data class looks like this:
We need to implement a new class that will ace as the Comparer:
All we have to do is to replace List.Sort() (Line 13) with:
And that is it, your list is sorted.
The hardest question is which one to choose. We know it is better than SortedList that is for sure…
I don’t yet know of any downfalls to anyone of them but I personally prefer the first one.
Tell me what you think and dont forget to read the previouse article about SortedList
Copyright © 2012 Dev102.com
Breeze : Designed by Amit Raz and Nitzan Kupererd