4

我正在这样做,C# .net2.0 我有一个包含两个字符串的列表,我想对其进行排序。清单就像List<KeyValuePair<string,string>>

我必须根据第一个对其进行排序string,即:

  • ACC
  • ABLA
  • 南德
  • 弗洛
  • IHNJ

我尝试使用Sort(),但它给了我异常:“无效操作异常”,“无法比较数组中的两个元素”

无论如何,你能建议我这样做吗?

4

4 回答 4

8

当您被 .NET 2.0 困住时,您将不得不创建一个实现IComparer<KeyValuePair<string, string>>并将其实例传递给Sort方法的类:

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

如果您要使用较新版本的 .NET 框架,则可以使用 LINQ:

list = list.OrderBy(x => x.Key).ToList();
于 2013-02-15T12:51:57.293 回答
5

为什么不使用 SortedDictionary 呢?

这是关于它的 MSDN 文章:

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

于 2013-02-15T12:56:54.673 回答
2

您可以只使用Comparison<T>通用委托。然后,您无需定义一个类来实现IComparer<T>,而只需要确保您定义您的方法以匹配委托签名。

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);
于 2013-02-15T13:25:59.987 回答
0
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();
于 2018-12-07T11:01:12.677 回答