Hi -
Does anyone know a way to created a SortedList (in the
System.Collections namespace) that will sort on VALUES instead of
KEYS... ?
The scenario is this - I have a SortedList containing key-value pairs
of UserID - DisplayName for a whole bunch of user objects. The UserID
is simply a long, the DisplayName is something like, "Jones, Bill". I
want the SortedList to sort the names alphabetically, rather than by
increasing order of UserIDs.
The simple answer is to use the DisplayName as a key, and UserID as a
value. However this barfs if I have multiple people with the same
DisplayName, as you can't have duplicate keys in a SortedList.
I know that I can override the IComparer that the SortedList uses for
comparisons, however, logistically I cannot think of a way to create
an IComparer that will be able to access the VALUES of the SortedList
collection. The problem is that I MUST supply the IComparer at
construction time of the SortedList; however the IComparer needs to
know about the SortedList so that when it is supplied with 2 keys to
sort, it can then access the values of the collection to work out
which comes before the other. And of course, I can't do something like
this -
SortedList sList = new SortedList(new MyComparer(sList));
for (hopefully) obvious reasons...
The other thing I tried was creating a "wrapper class" like this -
class SortedUserList : IComparer {
private SortedList userList = null;
public SortedList UserList {
get {
if (userList == null) {
userList = new SortedList(this);
}
return userList;
}
}
public SortedUserList() {
}
#region IComparer Members
public int Compare(object x, object y) {
string first = UserList[x] as string;
string second = UserList[y] as string;
return first.CompareTo(second);
}
#endregion
}
But this also didn't work - I got a Stack Overflow when I tried to add
the second user into the list.
I'm really hoping that there is a simple solution to this problem.
Thanks for your help,
gerrod