0

可能重复:
如何从字典中获取第 n 个元素?

如果有一个项目Dictionary总数,Y并且我们在<N时需要第一个项目,那么如何实现这一点?NY

例子:

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()

4

4 回答 4

3

ADictionary<K,V>没有任何内在顺序,因此实际上没有第 N 项这样的概念:

出于枚举的目的,字典中的每个项目都被视为 KeyValuePair<TKey, TValue>表示值及其键的结构。返回项目的顺序未定义。

话虽如此,如果您现在只想在 N 位置找到任意碰巧找到的项目,那么您可以使用ElementAt

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

(请注意,如果您再次运行相同的代码,或者即使您ElementAt快速连续调用两次,也不能保证在相同的位置找到相同的项目。)

于 2011-06-17T10:40:05.997 回答
2

字典未排序。没有第 n 项。

使用 OrderedDictionary 和 Item()

于 2011-06-17T10:40:09.923 回答
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)。

于 2011-06-17T10:39:27.567 回答
0

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

但是,请注意字典没有排序。根据您的要求,您可以使用SortedDictionary.

于 2011-06-17T10:39:24.400 回答