Sometimes you need a sorted list. You would think in that case the SortedList class would help out, but unfortunately this one only sorts based on the key, while most of the time you would like to sort based on the value. 

Now I can almost hear you think: "Why not switch key and value then?" Well, let’s say the key you would like to use is the username for a software program or a website. The value is the full name of the user. It is possible two different users have the same full name (John Smith), but have different usernames (j.smith and johns). In that case, switching keys and values won’t help you, because keys need to be unique in a SortedList.

To implement your own ‘sorted list’ which sorts based on the value, first create a class (or a struct) to hold the data for the key and the value you would like to retain in the list. Make sure you implement the IComparable interface, because you will need this to be able to sort the class/struct. For this example I implemented both key and value as a string:

public struct KeyValuePair : IComparable
{

    private string theKey;
    private string theValue;
           
    public string Key
    {
        get
        {
            return theKey;
        }
    }
 
    public string Value
    {
        get
        {
            return theValue;
        }
    }
 
    public KeyValuePair(string key, string value)
    {
        theKey = key;
        theValue = value;
    }
 
    public int CompareTo(object obj)
    {
        if (obj == null)
        {
            return 1;
        }
        else
        {
            KeyValuePair check = (KeyValuePair)obj;
            return Value.CompareTo(check.Value);
        }
    }
}
 
Now when you want a value-sorted list, you can simply create an ArrayList, add KeyValuePairs to the ArrayList, call the Sort() method (which calls the CompareTo() method for each of the objects that exist in the ArrayList) and see that the items in your ArrayList are sorted based on the values of all KeyValuePairs!!!

Sample:

    ArrayList arrayList;
    arrayList = new ArrayList();
    arrayList.Add(new KeyValuePair("1", "bbb"));
    arrayList.Add(new KeyValuePair("2", "ccc"));
    arrayList.Add(new KeyValuePair("3", "aaa"));
    arrayList.Sort();
    foreach (KeyValuePair keyValuePair in arrayList)
    {
        proofTextBox.Text += keyValuePair.Key + " : " + keyValuePair.Value + Environment.NewLine;
    }