gpt4 book ai didi

C# SortedList,按键取值

转载 作者:行者123 更新时间:2023-11-30 14:16:09 25 4
gpt4 key购买 nike

我有降序排列的 SortedList。

public class MyComparer : IComparer<int>
{
public int Compare(int x, int y)
{
if (x.CompareTo(y) > 0)
return -1;
return 1;
}
}
class Program
{
static void Main(string[] args)
{
SortedList<int, bool> myList = new SortedList<int, bool>(new MyComparer());
myList.Add(10, true);
bool check = myList[10];//In this place an exception "Can't find key" occurs
}
}

当在没有我自己的 IComparer 的情况下创建 SortedList 时,代码工作正常并且没有发生异常。

最佳答案

比较器实现无效;它违反了以下要求:

x.CompareTo(x) == 0 

当排序列表试图为给定键找到精确匹配项时,这会混淆排序列表。

这是一个简单的修复:

public int Compare(int x, int y)
{
return y.CompareTo(x); // Reverses the in-built comparison.
}

但如果您想更普遍地解决这个问题,请考虑创建一个 ReverseComparer<T> ,例如提供的 here .

关于C# SortedList,按键取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8193175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com