如何检索字典中的第 N 项?
可能的重复:
如何从字典中获取第 n 个元素?< /a>
如果有一个 Dictionary
总共有 Y
个项目,当 N
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()
?
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()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
字典
不会没有任何内在的顺序,所以实际上不存在第 N 项这样的概念:,如果您只想立即在位置 N 任意碰巧找到该项目,那么您可以使用
ElementAt
:(请注意,不能保证在同一位置找到相同的项目如果你运行相同的代码再次,或者即使您快速连续调用
ElementAt
两次。)A
Dictionary<K,V>
doesn't have any intrinsic ordering, so there's really no such concept as the Nth item: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
:(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.)字典未排序。没有第 n 项。
使用 OrderedDictionary 和 Item()
Dictionary isn't ordered. There is no nth item.
Use OrderedDictionary and Item()
使用 LINQ:
您可能希望使用
FirstOrDefault
而不是First
,具体取决于您对数据的了解程度。另外,请注意,虽然字典确实需要对其项目进行排序(否则它将无法迭代它们),但该排序是一个简单的 FIFO(它不可能是其他任何东西,因为
IDictionary< /code> 不要求您的项目是
IComparable
)。Using LINQ:
You might want to use
FirstOrDefault
instead ofFirst
, 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 beIComparable
).string item = items[items.Keys[1]];
但是,请注意字典未排序。根据您的要求,您可以使用
SortedDictionary
。string item = items[items.Keys[1]];
However, be aware that a dictionary isn't sorted. Depending on your requirements, you could use a
SortedDictionary
.