0

Possible Duplicate:
Collection was modified; enumeration operation may not execute - why?

First off, I believe this is NOT a duplicate question, as the context here deals with Extension methods.

I am getting this exception when moving items from one list to another via an Extension method, and I'm a bit confused because the list I'm removing items from is not the list I'm iterating over.

For example, the extension method at a minimum would look like this:

public static void MoveItemsTo(this IList source, IList target, IList items)
{
    foreach (var item in items) {
        target.Add(item);
        source.Remove(item);
    }
}

This is method is then called like this:

myCollectionOne.MoveItemsTo(myCollectionTwo, itemsToMove);

I only receive the error if I attempt to remove the item from the source list... This is a bit confusing as the method is iterating over a different list. Something must be going on behind the scenes that I am unaware of...

Community
  • 1
  • 1
danjarvis
  • 10,040
  • 3
  • 22
  • 21

2 Answers2

0

Instead of using a foreach loop, use a regular for loop. You're actually removing an item from the items list, since that's what you're iterating through.

for (int i = 0; i < items.Count; i++)
{
    target.Add(item);
    source.Remove(source[i]);
}

On a side note, you could probably just clear the entire source list in one go after the for loop, if that is indeed what you're trying to accomplish.

Jon Martin
  • 3,252
  • 5
  • 29
  • 45
0

This will return a new list that is the result of the item move from source to destination, without altering the source lists. This avoids the refence problem in the question by treating the sources lists as immutable lists.

void Main()
{
    var a = new List<string>() { "a","b","c" };
    var b = new List<string>() { "d" };
    var c = a.MoveItemsTo(i=>i=="b",b);
    c.Dump(); // { "d", "b" }
}

public static class Extensions
{
    public static IEnumerable<T> MoveItemsTo<T>(this IEnumerable<T> source, Func<T,bool> Predicate,IEnumerable<T> DestSource)
    {
        var newList = new List<T>(DestSource);
        newList.AddRange(source.Where(Predicate).ToList());
        return newList;
    }
}
asawyer
  • 17,642
  • 8
  • 59
  • 87