I’m trying to delete an entry from a dictionary (NOTE: Associative Array context). The deletion is based on a given number. Any number of keys can contain that number plus other text. What I’m doing currently is..
var results = from result in CGlobals.orders.Keys
where Regex.IsMatch(result, cmbJobNum.Text + "*")
select result;
foreach (string result in results)
CGlobals.orders.Remove(result);
I’m getting an invalid operation exception, which states that the collection was modified. What am I doing wrong here and how can I fix this?
The problem is the deferred execution in LINQ. Use this:
Explanation:
The deferred execution feature in LINQ executes the query not where you define it, but only when you enumerate it, i.e. in the
foreachloop. This means, you are looping over theCGlobals.orders.Keysenumeration and at the same time removing items from the dictionary which will update the keys enumeration.