By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,892 Members | 1,387 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,892 IT Pros & Developers. It's quick & easy.

Interesting Iterator Trivia - Thought I would share

P: n/a
Hello:

Yesterday, I encountered an interesting side-effect of iterators. Even
though the code looked fine, it actually was completely wrong. See if
you can figure out why this code doesn't do as it is expected and how
to fix it:

// Returns indicies of matching items
public static IEnumerable<intFindAll(IList<Tlist, Predicate<T>
predicate)
{
for (int i = 0; i != list.Count; ++i)
{
if (predicate(list[i]))
{
yield return i;
}
}
}

// Removes the items in the IList at the given indicies (if it's not
an T[])
public static void RemoveAt(IList<Tlist, IEnumerable<intindicies)
{
int shift = 0;
foreach (int index in indicies)
{
list.RemoveAt(index - shift);
++shift;
}
}

// Caller
List<intvalues = new List<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8,
9 });
IEnumerable<intindicies = FindAll<int>(values, delegate (int
current) { return i % 2 == 0; });
RemoveAt(values, indicies);
I just forced the RemoveAt method to take the predicate, but there is
a way to fix the caller withouth touching the other methods.

Have fun,
Travis
Jul 11 '08 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.