问题
Possible Duplicate:
How do I get the nth element from a Dictionary?
If there's a Dictionary
with total of Y
items and we need N
th item when N
< Y
then how to achieve this?
Example:
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);
How to write GetNthItem()
?
回答1:
Dictionary isn't ordered. There is no nth item.
Use OrderedDictionary and Item()
回答2:
A Dictionary<K,V> doesn't have any intrinsic ordering, so there's really no such concept as the Nth item:
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.
Having said that, if you just want the item that arbitrarily happens to be found at position N right now then you could use ElementAt:
string item = items.ElementAt(2).Value;
(Note that there's no guarantee that the same item will be found in the same position if you run the same code again, or even if you call ElementAt
twice in quick succession.)
回答3:
Using 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();
You might want to use FirstOrDefault
instead of First
, depending on how much you know about your data.
Also, be aware that while dictionary does need an ordering for its items (otherwise it wouldn't be able to iterate over them), that ordering is a simple FIFO (it couldn't easily be anything else, since IDictionary
does not require your items to be IComparable
).
回答4:
string item = items[items.Keys[1]];
However, be aware that a dictionary isn't sorted. Depending on your requirements, you could use a SortedDictionary
.
来源:https://stackoverflow.com/questions/6384528/how-to-retrieve-nth-item-in-dictionary