Removing a Dictionary Entry With a Regex
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, wh开发者_StackOverflow中文版ich 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:
var results = (from result in CGlobals.orders.Keys
where Regex.IsMatch(result, cmbJobNum.Text + "*")
select result).ToList();
foreach (string result in results)
CGlobals.orders.Remove(result);
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 foreach
loop. This means, you are looping over the CGlobals.orders.Keys
enumeration and at the same time removing items from the dictionary which will update the keys enumeration.
The problem is that LINQ produces its results as you ask for them rather than all at once.
You need something like foreach (string result in results.ToArray())
.
精彩评论