我在这里读到,与SortedList不同,SortedDictionary不允许索引检索.那么我如何nameAddr["C"]在以下代码片段中正确获取?
SortedDictionary<string, string> nameAddr = new SortedDictionary<string, string>();
nameAddr.Add("X", "29");
nameAddr.Add("A", "30");
nameAddr.Add("C", "44");
Console.WriteLine(nameAddr["C"]);
Run Code Online (Sandbox Code Playgroud)
这是按密钥索引.SortedList允许通过"key of index"进行索引,例如nameAddr.Values[1]返回"44".
(该集合不允许对名称/值对进行索引,仅对每个Keys和Values单独进行索引.)
例如:
var list = new SortedList<string, string>
{
{ "X", "29" },
{ "A", "30" },
{ "C", "44" },
};
Console.WriteLine(list.Keys[1]); // Prints "C"
Console.WriteLine(list.Values[1]); // Prints "44"
Run Code Online (Sandbox Code Playgroud)
SortedList在内部使用数组作为存储的数据结构,然后根据需要对数组进行排序以保持项目的顺序.由于它使用数组,因此可以使用数字索引访问项目,就像使用任何数组一样.
SortedDictionary在内部使用红黑二进制搜索树来保持项目的顺序.这个概念完全不同.没有数组,也没有用于通过数字索引检索项目的模拟.您唯一的选择是使用添加到字典中的键值对的键部分.
照这样说.你的代码对我来说是正确的.这是从字典中检索项目的唯一方法(除了使用Values集合之外,但这也不会为您提供数字索引功能).