Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 20th, 2012  |  syntax: None  |  size: 0.83 KB  |  hits: 11  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Why Removing item from list in this way is impossible?
  2. public void RemoveFrmList(int ProdId)
  3.         {
  4.             int _index;
  5.             foreach (Products item in BoughtItems)
  6.             {
  7.                 if (item.ProductID == ProdId)
  8.                 {
  9.                    _index = BoughtItems.IndexOf(item);
  10.                 }
  11.  
  12.             }
  13.             BoughtItems.RemoveAt(_index);
  14.         }
  15.        
  16. int _index;
  17. foreach (Products item in BoughtItems)
  18. {
  19.    //Code here is not executed during runtime for reasons stated above.
  20. }
  21. BoughtItems.RemoveAt(_index); //error here because _index was not assigned!
  22.        
  23. int _index = -1;
  24. foreach (...)
  25. {
  26.    //...
  27. }
  28. if (_index != -1){
  29.    BoughtItems.RemoveAt(_index);
  30. }
  31. else
  32. {
  33.   //handle case if needed
  34. }
  35.        
  36. public void RemoveFrmList(int ProdId)
  37. {
  38.     BoughtItems.RemoveAll( item => item.ProductID == ProdId );
  39. }