c#SortedList.ContainsKey表示成功添加key返回false检查下方更新3我发现我在.Net4.0,4.0上遇到的问题客户端是与4.5的c#字符串比较器的一个已知严重问题有关,这会导致字符串列表以不一致的顺序排序(导致输出取决于输入的顺序和使用的排序算法)。该问题已于2012年12月报告给Microsoft,并以“Won'tfix”结束。有一种解决方法,但速度要慢得多,而且对于大型集合来说几乎不实用。在实现不可变的PatriciaTrie时,我想将其性能与System.Collections.Generic.SortedList进行比较。我使用以下文件https://github.com/rkapsi/patricia-trie/blob/master/src/test/resources/org/ardverk/collection/hamlet.txt创建用于测试的输入词汇表。在c#SortedList中插入每个单词时,使用Comparer.Default或StringComparer.InvariantCulture作为键比较器,无法检索使用正常搜索方法成功插入的多个条目(例如ContainsKey返回false),但通过迭代列表观察到的键存在于列表中。更奇怪的是,当比较从排序列表中检索到的键与使用ContainsKey找不到的搜索键时,比较器返回值“0”。下面的完整示例演示了我系统上的这个问题。使用系统;使用System.IO;使用System.Linq;使用System.Collections.Generic;classProgram{staticvoidMain(string[]args){//问题可能与比较有关。变种失败=真;变种比较器=失败?StringComparer.InvariantCulture:StringComparer.Ordinal;//读取hamlet(包含重复的单词)varwords=File.ReadAllLines("hamlet.txt").SelectMany(l=>l.Split(new[]{'','t'},StringSplitOptions.RemoveEmptyEntries)).选择(w=>w.Trim()).Where(w=>!string.IsNullOrEmpty(w)).Distinct(比较器).ToArray();//将hamlet的单词插入排序列表中。varlist=newSortedList(比较器);varndx=0;foreach(varwordinwords)list[word]=ndx++;//搜索每个添加的单词。foreach(varkeyToSearchinwords){if(!list.ContainsKey(keyToSearch)){//已插入,但无法检索。Console.WriteLine("错误-未找到密钥:"{0}"",keyToSearch);//但是当我们遍历列表时,我们看到条目存在varprefix=keyToSearch.Substring(0,Math.Min(keyToSearch.Length,3));foreach(varwordCloseToSearchKeyinlist.Keys.Where(s=>s.StartsWith(prefix))){//并使用SortedList提供的比较返回0,表示相等varcomparisonResult=list.Comparer.Compare(wordCloseToSearchKey,keyToSearch);Console.WriteLine("{0}-比较结果={1}",wordCloseToSearchKey,comparisonResult);}}}//检查List.Keys的排序顺序是否正确varkeys=list.Keys.ToArray();BinarySearchAll("list.Keys",keys,list.Comparer);CheckCorrectSortOrder("list.Keys",keys,list.Comparer);//检查Array.Sort(List.Keys)的排序顺序是否正确vararraySortedKeys=CopySortSearchAndCheck("Array.Sort(List.Keys)",keys,list.Comparer);//检查Array.Sort(inputwords)的排序顺序是否正确varsortedInput=CopySortSearchAndCheck("Array.Sort(inputwords)",words,list.Comparer);安慰。读线();}staticstring[]CopySortSearchAndCheck(stringarrayDesc,string[]input,IComparercomparer){//复制输入varsortedInput=newstring[input.Length];Array.Copy(输入,sortedInput,sortedInput.Length);//排序Array.Sort(sortedInput,comparer);//检查我们是否真的可以使用bin找到数组中的键。搜索BinarySearchAll(arrayDesc,sortedInput,比较器);//检查排序顺序是否正确CheckCorrectSortOrder(arrayDesc,sortedInput,comparer);返回排序输入;}staticvoidBinarySearchAll(stringarrayDesc,string[]sortedInput,IComparercomparer){//检查是否可以使用bin找到输入中的每个键。searchforeach(varwordinsortedInput){varix=Array.BinarySearch(sortedInput,word,comparer);if(ix<0)//看来它不能!Console.WriteLine("错误-{0}-未找到密钥:"{1}"",arrayDesc,word);}}staticvoidCheckCorrectSortOrder(stringarrayDesc,string[]sortedKeys,IComparer比较器){for(intn=0;n
