c# - Item removed from one collection is removed from second collection implicitly too, why? -


this big confusion me. have following code:

ienumerable<workflowstatedata> data = model.data.except(             request.workflowstate.customdata.select(x => new model.workflowstatedata {key = x.key}),             new workflowstatedataequalitycomparer());         foreach (var item in data) // makes comparison (and exception) based on value of property 'key'         {             model.data.remove(item);             statedataset.remove(item);         }  

this should create new collection of items , use enumeration using foreach. should remove items original collection, removes both original collection , "data" collection , throws invalidoperationexception: collection modified. why?

enumerable.except returns ienumerable<t> of set difference deferred means still query. everytime "touch" data execute query. if want "materialized" collection have use tolist, toarray, tolookup or todictionary (or add result foreach-loop collection).

normally should exception if try modify collection enumerating in foreach. use tolist create real collection not afffected if modify it's source:

list<workflowstatedata> data = model.data.except(         request.workflowstate.customdata.select(x => new model.workflowstatedata {key = x.key}),         new workflowstatedataequalitycomparer())     .tolist(); 

now can remove object(s) original collection without removing list.

you should read linq's deferred execution / eager evaluation.


Comments