简体   繁体   中英

Sort list<keyValuePair<string,string>>

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?

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();

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

You could just use the Comparison<T> generic delegate. Then you avoid the need to define a class just to implement IComparer<T> but rather just need to ensure that you define your method to match the delegate signature.

private int CompareByKey(KeyValuePair<string, string>, KeyValuePair<string, string> y)
{
    if (x.Key == null & y.Key == null) return 0;
    if (x.Key == null) return -1;
    if (y.Key == null) return 1;

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

list.Sort(CompareByKey);
List<KeyValuePair<string, string>> pairs = new List<KeyValuePair<string, string>>();
pairs.Add(new KeyValuePair<string, string>("Vilnius", "Algirdas"));
pairs.Add(new KeyValuePair<string, string>("Trakai", "Kestutis"));

pairs.Sort(delegate (KeyValuePair<String, String> x, KeyValuePair<String, String> y) { return x.Key.CompareTo(y.Key); });
foreach (var pair in pairs)
     Console.WriteLine(pair);
Console.ReadKey();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM