locked
Collection was modified; enumeration operation may not execute. RRS feed

  • Question

  • User467339115 posted

    Hello,
    I have this code:

                    List<ProductList_Products> Citems = new List<ProductList_Products>();
                    List<ProductList_Products> Ditems = new List<ProductList_Products>();
                    Citems = viewModel.plist;
                    Ditems = viewModel.plist;
    
                    foreach (ProductList_Products Citem in Citems)
                    {
                        int InMastercatAlso = 0;
    
                        InMastercatAlso = (from item in storedb.DJPMVCProductsByCats
                                           where item.CatGUID == MasterSortGuid && item.ProductKey == Citem.product_Key
                                           select item).Count();
    
                        if (InMastercatAlso == 0)
                        {
                            Ditems.Remove(Citem);
                        }
                    }
                    viewModel.plist = Ditems;


    I dont modify Citems for the fornext loop, so why do i get "Collection was modified; enumeration operation may not execute. "
    on the line "foreach (ProductList_Products Pitem in Citems) "

    I know why its happening I dont know how to code the way around it......

    please help with code examples...

    Thursday, August 9, 2012 3:36 PM

Answers

  • User197322208 posted

    Citems = viewModel.plist;
                    Ditems = viewModel.plist;

    CItems and DItems are same collection

    Maybe you want

    Citems.AddRange(viewModel.plist);
    Ditems.AddRange(viewModel.plist);

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 9, 2012 3:47 PM
  • User467339115 posted

    I acually did this

           Citems = viewModel.plist.ToList();
                    Ditems = viewModel.plist.ToList();
    and it worked...
     
    thanks you had the same idea...
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 9, 2012 4:06 PM

All replies

  • User197322208 posted

    Citems = viewModel.plist;
                    Ditems = viewModel.plist;

    CItems and DItems are same collection

    Maybe you want

    Citems.AddRange(viewModel.plist);
    Ditems.AddRange(viewModel.plist);

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 9, 2012 3:47 PM
  • User467339115 posted

    I acually did this

           Citems = viewModel.plist.ToList();
                    Ditems = viewModel.plist.ToList();
    and it worked...
     
    thanks you had the same idea...
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 9, 2012 4:06 PM