我有以下字典内容:
[0] {75, SimpleObject}
[1] {56, SimpleObject}
[2] {65, SimpleObject}
[3] {12, SimpleObject}
...
Run Code Online (Sandbox Code Playgroud)
我希望得到第一把钥匙,意味着75,没有foreach.
也许这个key
词应该引用[0]而不是75.
因为基于该键,我想使用它SimpleObject
,我写道:
SimpleObject s = dictionary[0] as SimpleObject;
Run Code Online (Sandbox Code Playgroud)
但是VS2010引发了一个异常:
The given key was not present in the dictionary.
Run Code Online (Sandbox Code Playgroud)
我知道这[0]
意味着字典中的键号0,意味着我可以拥有
[0] {72, SimpleObject} //here
[1] {56, SimpleObject}
[2] {65, SimpleObject}
[3] {12, SimpleObject}
...
Run Code Online (Sandbox Code Playgroud)
那我应该找通讯员SimpleObject
.
对不起,是第一次使用词典,我想了解更多.
问题:如何获取数字75
和他的SimpleObject?
谢谢.
PS:我知道在StackOverflow中已经存在类似的主题,但它们中没有一个能帮助我获得该密钥.
Sam*_*ham 10
using System.Linq;
...
dictionary.First().Key // Returns 75
dictionary.First().Value // returns the related SimpleObject
Run Code Online (Sandbox Code Playgroud)
这不是Dictionary<TKey, TValue>
一个无序的集合,因此它没有第一个或最后一个概念.呈现的项目的顺序基本上是随机的.您不能依赖于应用程序实例之间的相同.
如果你确实想要一些订单,那么你应该使用SortedDictionary<TKey, TValue>
.这里提供的项目是以有序的方式完成的,并且可以在您的应用程序运行之间提供一致的结果
// Consistent output is produced below
var dictionary = new SortedDictionary<int, SimpleObject>();
var pair = dictionary.First();
Console.WriteLine("{0} -> {1}", pair.Key, pair.Value);
Run Code Online (Sandbox Code Playgroud)