C#SortedList,按键获取值
发布时间:2020-12-16 09:38:38 所属栏目:百科 来源:网络整理
导读:我按降序排列了SortedList. public class MyComparer : IComparerint { public int Compare(int x,int y) { if (x.CompareTo(y) 0) return -1; return 1; } }class Program{ static void Main(string[] args) { SortedListint,bool myList = new SortedListi
我按降序排列了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提供的那个. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |