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

时间:2011-08-08 13:55:21

标签: 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;
     }
 }

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

4 个答案:

答案 0 :(得分:2)

尝试LINQ按条件查找项目索引:

int index = dictionary.TakeWhile(condition).Count();

如果您可以将您的条件提取到Func中,您也可以在SkipWhile()中重复使用它:

Func<int, bool> condition = (key) => { return key == "textToSearch"; };
int index = dictionary.TakeWhile(item => condition(item.Key)).Count();

// use inverted condition
var secondPart = dictionary.SkipWhile(item => !condition(item.Key));

PS:如果表现很重要,那将不是最好的解决方案

答案 1 :(得分:2)

您可以放弃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;
      }
}

答案 2 :(得分:1)

答案 3 :(得分:0)

foreach切换到for循环,并在循环外声明循环的索引,如:

int pairIndex = 0;
for(i = 0; i<5; i++)
{
    for (; pairIndex < dictionary.Count; pairIndex++)
    {
          KeyValuePair<string, string> pair = dictionary.ElementAt(pairIndex);
          /* do something */
          if(consdition) break;
     }
 }