I’m working on a web application prototype and I’m using some dummy data in xml form because it is simple and I don’t want to care about the database for a prototype ;)
Let say this is my sample data :
<root> |
I have some drop down lists or combo boxes to fill in with this kind of data in the form, and I want them to be sorted based on the description (name) not based on the key (id).
Since the data come from xml file, it may not be sorted that way, so I need to find a way to sort the data first and then bind the values to the drop down lists.
Firstly I thought it will be very simple, only need to create a class which implements IComparer for this and use it in the available generic collection types. However, it only true at the new IComparer class, but not on the generic collection part, I found out that SortedDictionary<TKey, TValue> and SortedList<TKey, TValue> will use the key to sort, even though we can specify the IComparer in the constructor.
So based on the forum discussion, I found that we can use a generic List<T> to perform sorting and we can use KeyValuePair<TKey, TValue>as the type of T.
Here is the SortByValueComparer class which implements IComparer :
public class SortByValueComparer<TKey, TValue> : IComparer<KeyValuePair<TKey, TValue>> public int Compare(KeyValuePair<TKey, TValue> x, KeyValuePair<TKey, TValue> y) #endregion |
Then we can use List<T> such as :
[Fact] Assert.Equal(l[0].Value, "Jeff"); // Sort the collection based on the value Assert.Equal(l[0].Value, "Andy"); |
However, I felt that the code is a bit cluttered, so I add a new Custom List class which implements List<T> :
public class CustomList<TKey, TValue> : List<KeyValuePair<TKey, TValue>> public void AddEntry(TKey key, TValue value) public void SortByValue() |
So I can use it like this :
[Fact] Assert.Equal(l[0].Value, "Jeff"); // Sort the collection based on the value Assert.Equal(l[0].Value, "Andy"); |
Hope this helps ;)
2 comments:
Great post...helped me out a lot on a particular problem!
I must learn to operate this all is C++...Oh its not so easy for me sir!
r4 revolution