2011-06-17 57 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兩次。)