Program crashes at List.Remove(Item) !!?? RRS feed

  • Question

  • hi,why my program crashes at these line :

           List <DateTime> dt = new List<DateTime>();

                   foreach (string date in Dates)                     ///Dates list stores dates like "1/1/2012"

                foreach (DateTime dt_ in dt)
                    if (dt_ > Convert.ToDateTime(End_Date))
                    else if (dt_ < Convert.ToDateTime(Begin_Date))


    if conditions occurs and something removes from list then program crashes.why ?


    • Edited by muupp Thursday, August 2, 2012 3:38 PM
    Thursday, August 2, 2012 3:36 PM


  • This is more a C# forum question, but when you are in a foreach loop, you cannot remove items from collection. Best way is to have another collection and add removable items to it, then after foreach ends, iterate through that collection and the remove them from original collection that way.

    Also doing a Convert.ToDateTime everytime for each dt_ is very inefficient, do it once before the loop and assign it ot a variable and use that variable.

    Good luck and happy coding.

    noorbakhsh حميد نوربخش

    • Edited by noorbakhsh Thursday, August 2, 2012 3:43 PM
    • Marked as answer by muupp Thursday, August 2, 2012 4:36 PM
    Thursday, August 2, 2012 3:41 PM