Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list<keyValuePair<string,string>>

Tags:

c#

.net

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?

like image 931
sudhanshu Avatar asked Dec 07 '22 09:12

sudhanshu


2 Answers

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();
like image 152
Daniel Hilgarth Avatar answered Dec 14 '22 23:12

Daniel Hilgarth


Why not use a SortedDictionary instead?

Here's the MSDN article on it:

http://msdn.microsoft.com/en-us/library/f7fta44c(v=vs.80).aspx

like image 41
Mike Parkhill Avatar answered Dec 14 '22 23:12

Mike Parkhill