Search code examples
c#linqdictionaryienumerableset-difference

Most efficient way to remove items from a list without running into a collection modified exception?


I have 2 lists:

ListA { 'A', 'B', 'C' } //ListA is DictA.Keys
ListB { 'B', 'X', 'Y' } //ListB is DictB.Keys

If I do ListA.Except(ListB) I get an ExceptIterator returned which will let me iterate over ListA for any item that isn't in ListB. The problem is that it's implementation is to simply use ListA as well (for some reason I thought it would create a new collection of items that are the difference). Well, low and behold I come to find out that it's still using ListA as the source, but simply using a special type of iterator. So, of course when I remove an item from ListA it complains that the collection has been modified.

I can think of a couple of ways to do what I want, first of which is to Copy ListA and do the Except on the copy. The second is to just do a while loop. I'm just wondering what the best solution to this problem is, and what follows standard guidelines.

If I'm going about this the wrong way, I'd love to know that. My key goal is to remove everything from a DictA that is not in DictB using the keys as comparisons.


Solution

  • If you need the result to stick around and be independent of later changes, simply get a concrete result by invoking ToList() or ToArray() on the query.

    var query = list1.Except(list2).ToList(); 
    

    Changes to either source input will have no impact on your now fully-evaluated query.