0

I need to delete matching elements from list. How can I correctly do that? This is my code, but it crashes with the error "collection was modified".

private List<Product> ClearMatching(List<Product> allNewProducts)
{
    var allProductUralbug = allNewProducts.Where(x => x.Supplier == "oneValue").ToList();
    var allProductUragalant = allNewProducts.Where(x => x.Supplier == "twoValue").ToList();
    foreach (var productBug in allProductUralbug)
    {
        foreach (var productGalang in allProductUragalant)
        {
                if (productGalang.Sku == productBug.Sku)
                {
                    allProductUragalant.Remove(productGalang);
                }      
        }
    }
    allProductUragalant.AddRange(allProductUralbug);
    return allProductUragalant;
}
Brian
  • 14,610
  • 7
  • 35
  • 43
  • You're modifying `allProductUragalant` while looping through it, which isn't allowed. See the question that this was marked as a duplicate of for more details. – Brian Dec 23 '16 at 19:31
  • Why are you adding matching elements in the first place? Can you not only add elements that don't already exist? – Dour High Arch Dec 23 '16 at 20:05

0 Answers0