c# 获取迭代器在字典中的位置

标签 c# .net iterator

我有一个 Dictionary<string,string>然后我遍历它的 KeyValuePairs。但我的问题是我需要在某个时候停止迭代并从同一位置继续迭代。我的代码如下。

for(i = 0; i<5; i++)
{
    foreach(var pair in dictionary) /* continue from iterators last position */
    {
          /* do something */
          if(consdition) break;
     }
 }

代码不是很清楚,但我希望我正在尝试做的是。我该怎么办?

最佳答案

你可以放弃 foreach并致力于 IEnumerator<T>直接。

using (IEnumerator<<KeyValuePair<K,V>> enumerator = dict.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        DoSomething(enumerator.Current);
        if (condition)
            break;
    }

    while (enumerator.MoveNext())
    {
        DoMoreWork(enumerator.Current);
    }
}

但您可能会考虑重构代码,以便 foreach是外环。这可能更容易和更清洁。

int i=0;
foreach(var pair in dictionary)
{
      if(condition)
      {
         DoSomething();
         i++;
         if(i<5)
           continue;
         else
           break;
      }
}

关于c# 获取迭代器在字典中的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6983196/

相关文章:

c# - async/await 抛出 NullReferenceException 我们如何诊断哪里搞砸了?

.net - 清除 PIN 缓存智能卡

c# - NuGet 更新后的 FileLoadException

c# - c# 中的正则表达式找到字母然后\用大写字母作为字母和 Shift 按下其他字符的形式?

c++ - 从存储在集合中的数字计算 vector 中的 int?

c# - NaN 对 double 意味着什么?

c# - 在 gridview 中隐藏选择按钮

c# - 如何通过公用名更快地检索 Active Directory 用户?

python - 为什么排序后查询表会慢很多?

使用 STL 算法与容器(char * 除外)进行 C++ 二进制文件 I/O