Program crashes at List.Remove(Item) !!??
-
Donnerstag, 2. August 2012 15:36
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
Alle Antworten
-
Donnerstag, 2. August 2012 15:41
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 حميد نوربخش
- Bearbeitet noorbakhsh Donnerstag, 2. August 2012 15:42
- Bearbeitet noorbakhsh Donnerstag, 2. August 2012 15:43
- Als Antwort markiert muupp Donnerstag, 2. August 2012 16:36

