Sort list<keyValuePair<string,string>>

.net, c#

Solution

As you are stuck with .NET 2.0, you will have to create a class that implements `IComparer<KeyValuePair<string, string>>` and pass an instance of it to the `Sort` method:

public class KvpKeyComparer<TKey, TValue> : IComparer<KeyValuePair<TKey, TValue>>
    where TKey : IComparable
{
    public int Compare(KeyValuePair<TKey, TValue> x,
                       KeyValuePair<TKey, TValue> y)
    {
        if(x.Key == null)
        {
            if(y.Key == null)
                return 0;
            return -1;
        }

        if(y.Key == null)
            return 1;

        return x.Key.CompareTo(y.Key);
    }
}

list.Sort(new KvpKeyComparer<string, string>());

If you would use a newer version of the .NET framework, you could use LINQ:

list = list.OrderBy(x => x.Key).ToList();

Problem

I am doing it in `C#` `.net2.0` I am having a list which contains two strings and i want to sort it. list is like `List<KeyValuePair<string,string>>` I have to sort it according to the first `string`, which is: - ACC - ABLA - SUD - FLO - IHNJ I tried to use `Sort()`, but it gives me the exception: "Invalid operation exception","Failed to compare two elements in array". Can you suggest me anyway in which I can do this?

Original source