locked
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"
                       dt.Add(Convert.ToDateTime(date));

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

    }

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

    thanks



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

Answers

  • 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