Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# get iterator position in dictionary

Tags:

iterator

c#

.net

I have a Dictionary<string,string> and I iterate over its KeyValuePairs. But my issue is that I need to stop the iteration at some point and continue the iteration from the same position. My code is as follows.

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

The code is not very clear but I hope my what I'm trying to do is. What do I do?

like image 575
Aks Avatar asked Mar 05 '26 17:03

Aks


2 Answers

You could abandon foreach and work on the IEnumerator<T> directly.

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

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

But you might consider refactoring the code so that foreach is the outer loop. That's probably easier and cleaner.

int i=0;
foreach(var pair in dictionary)
{
      if(condition)
      {
         DoSomething();
         i++;
         if(i<5)
           continue;
         else
           break;
      }
}
like image 102
CodesInChaos Avatar answered Mar 07 '26 07:03

CodesInChaos


Try out LINQ to find item index by condition:

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

If you can extract your condition into a Func you can reuse it in SkipWhile() as well:

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: if performance is matter it won't be the best solution

like image 23
sll Avatar answered Mar 07 '26 07:03

sll



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!