【发布时间】:2021-01-10 16:45:06
【问题描述】:
我有一本包含 4 个 KeyValuePair 项的字典。现在我有 2 个 foreach 循环(循环 1 和循环 2),这是我想要实现的目标:
循环1:
使用此 foreachloop 遍历前 2 个项目。
循环2:
使用这个 foreachloop 遍历项目 3-4。
我不确定这是否可行,因此我尝试了这个:
@for (int DictItem = 0; i < finalDictionary.Count; DictItem++)
{
var test = finalDictionary[i];
if(test == 1 || test == 2)
{
//First 2 items
}
if(test == 3 || test == 4)
{
//3th and 4th items
}
}
这里我试图通过 for 循环的索引获取 KeyValuePair,但这不起作用。
提前致谢
【问题讨论】:
-
字典没有排序,顺便说一句 - 所以存在“范围”键的想法是错误的。当然,您可以缓冲所有键,然后对它们进行排序,然后遍历其中的一个范围。
-
你的
finalDictionary是什么类型的?看起来像Dictionary<Int32,Int32>,对吗?它代表什么? -
它是一个嵌套字典:@foreach (KeyValuePair
>> entry in finalDictionary)
标签: c# loops for-loop foreach iterator