For example
var query = myDic.Where(x => !blacklist.Contains(x.Key));
foreach (var item in query)
{
if (condition)
blacklist.Add(item.key+1); //key is int type
ret.add(item);
}
return ret;
would this code be valid? and how do I improve it?
Updated
i am expecting my blacklist.add(item.key+1) would result in smaller ret then otherwise. The ToList() approach won’t achieve my intention in this sense.
is there any other better ideas, correct and unambiguous.
That is perfectly safe to do and there shouldn’t be any problems as you’re not directly modifying the collection that you are iterating over. Though you are making other changes that affects where clause, it’s not going to blow up on you.
The query (as written) is lazily evaluated so
blacklistis updated as you iterate through the collection and all following iterations will see any newly added items in the list as it is iterated.The above code is effectively the same as this:
So what you should get out of this is that as long as you are not directly modifying the collection that you are iterating over (the item after
inin theforeachloop), what you are doing is safe.If you’re still not convinced, consider this and what would be written out to the console: