24

for example:

1.

         foreach (var item in myDic)
                {
                  if (item.value == 42)
                        myDic.remove(item.key);
                }

would the iterator works properly no matter how the statements in the inner brackets could possibly affect myDic?

2.

    var newDic = myDic.where(x=>x.value!=42).ToDictionary(x=>x.key,x=>x.value);

Is 2nd approach a good practice? functional programming and immutable?

4 Answers 4

42

The first approach will crash at runtime, since the enumerator makes sure that nobody deletes from the underlying collection while it's enumerating.

The second approach is a nice thought, but C# dictionaries are mutable and it's neither idiomatic nor efficient to copy them around if you can accomplish the same thing with mutation.

This is a typical way:

var itemsToRemove = myDic.Where(f => f.Value == 42).ToArray();
foreach (var item in itemsToRemove)
    myDic.Remove(item.Key);

EDIT: In response to your question in the comments. Here's how the example in your other question works:

myList = myList.where(x=>x>10).select(x=>x-10);

This line of code doesn't run anything; it's totally lazy. Let's say for the sake of argument that we have a foreach after it to make it look more like this question's example.

foreach (int n in myList)
    Console.WriteLine(n);

When that executes, here's what'll happen on each iteration:

  1. Call MoveNext on the enumerator
  2. The enumerator finds the next value greater than ten
  3. Then it takes that value minus ten and sets the Current property to that
  4. Binds the Current property to the variable n
  5. Console.WriteLines it

You can see that there's no mystery and no infinite loop and no whatever.

Now compare to my example, supposing we left out the ToArray.

var itemsToRemove = myDic.Where(f => f.Value == 42);
foreach (var item in itemsToRemove)
    myDic.Remove(item.Key);
  1. Call MoveNext on the enumerator
  2. The enumerator finds the next pair with value 42 and sets the Current property to that
  3. Binds the Current property to the variable item
  4. Removes it

This doesn't work because while it's perfectly fine to WriteLine something from a collection while you have an enumerator open on it, you aren't permitted to Remove something from a collection while you have an enumerator open on it.

If you call ToArray up front, then you start out by enumerating over the dictionary and populating the array. When we get to the foreach, the foreach statement has an enumerator open on the array, not the dictionary. You're allowed to remove from the dictionary as you iterate over the array.

9
  • ToList() is faster than ToArray().
    – SLaks
    Aug 24, 2011 at 13:37
  • The performance difference is insignificant enough that I usually just prefer whichever seems more semantically correct (that is, if I don't plan on adding or removing, I stick with ToArray.)
    – mqp
    Aug 24, 2011 at 13:38
  • 3
    No, you can't omit it. If you left it lazy, then it would still be enumerating over the dictionary when Remove is called, and you'd be right back where you started (with an exception at runtime.) You need to do all the work to build the list of items to remove before you actually start removing any.
    – mqp
    Aug 24, 2011 at 13:42
  • 1
    @mquander: Have you missed .select(x=>x.key) in order to reform the dictionary into list?
    – colinfang
    Aug 24, 2011 at 14:14
  • 1
    Why not a one-liner? myDic.Where(kvp => kvp.Value == 42).ToList.ForEach(kvp => myDic.Remove(kvp.Key));
    – ErikE
    Nov 25, 2015 at 20:00
16

Also you can iterate over the copy of your collection:

foreach (var item in myDic.ToList())
{
    if (item.value == 42)
    myDic.remove(item.key);
}

notice myDic.ToList() in foreach statement.

0
12

According to the docs, starting from .NET Core 3.0, removing an element will no longer affect active enumerators. You can safely remove an item while iterating:

foreach (var item in myDic)
{
    if (item.Value == 42)
        myDic.Remove(item.Key);
}

Dictionary<TKey,TValue>.Remove Method

.NET Core 3.0+ only: this mutating method may be safely called without invalidating active enumerators on the Dictionary<TKey,TValue> instance. This does not imply thread safety.

2
  • amazing, how did u notice this? Is there any more in depth details how they manage to implement that internally? I am unable to find it in .net core release note
    – colinfang
    Feb 17, 2022 at 17:46
  • @colinfang Having read this thread, I stumbled upon this while investigating the performance of the Remove method in the docs. So decided to post an update. Feb 17, 2022 at 21:06
0

I would suggest making a copy of the keys and not the entire dictionary as an array, like others have suggested.

mykeytype[] mykeys = new mykeytype[mydic.Keys.Count];
mydic.Keys.CopyTo(mykeys, 0);
foreach (var key in mykeys)
{
    MyType thing;
    if (!mydic.TryGetValue(key, out thing)) continue;

    // remove or add to dictionary here
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.