2011-06-17 53 views
0

可能重复:
How do I get the nth element from a Dictionary?如何检索字典中的第N个项目?

如果有,总的YDictionary,我们需要N个项目时N < Y那么如何实现这一目标?

例子:

Dictionary<int, string> items = new Dictionary<int, string>(); 

items.add(2, "Bob"); 
items.add(5, "Joe"); 
items.add(9, "Eve"); 

// We have 3 items in the dictionary. 
// How to retrieve the second one without knowing the Key? 

string item = GetNthItem(items, 2); 

如何写GetNthItem()

+2

字典都不具备的顺序内置到他们的概念。如果你需要知道这个信息,字典(可能)不是正确的结构使用。 – dlev 2011-06-17 10:40:32

回答

2

字典是没有顺序。没有第n项。

使用OrderedDictionary和Item()

0

string item = items[items.Keys[1]];

但是,要知道,一个字典是没有排序。根据您的要求,您可以使用SortedDictionary

1

使用LINQ:

Dictionary<int, string> items = new Dictionary<int, string>(); 

items.add(2, "Bob"); 
items.add(5, "Joe"); 
items.add(9, "Eve"); 

string item = items.Items.Skip(1).First(); 

你可能想使用FirstOrDefault代替First,这取决于你知道你的数据有多大。

另外,请注意,虽然字典确实需要对其项目进行排序(否则它将无法遍历它们),但这种排序是一个简单的FIFO(它不能轻易成为其他任何东西,因为IDictionary不需要你的物品是IComparable)。

3

一个Dictionary<K,V>没有任何内在的顺序,所以真的没有这样的概念的第N项:

For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair<TKey, TValue> structure representing a value and its key. The order in which the items are returned is undefined.

话虽如此,如果你只是想要的项目是任意发生在位置N现在那么你可以使用ElementAt

string item = items.ElementAt(2).Value; 

(请注意,有没有保证,同样的项目将在相同的位置可以找到,如果你再次运行相同的代码,或者即使你连续快速地调用ElementAt两次。)