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?
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;
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With