Skip to content

Take advantage of Remove being allowed during Dictionary<K,V> enumeration #27006

@danmoseley

Description

@danmoseley

Now CoreFX has picked up the CoreCLR side of https://github.com/dotnet/corefx/issues/29979, we take advantage of it in CoreFX code.

We need to find code like this

var removes = new List<object>();
foreach(var entry in dict)
{
    if (predicate(entry.Key))
            removes.Add(entry.Key);
}
foreach(var entry in removes)
{
    dict.Remove(entry);
}

or equivalently in Linq

foreach (var entry in dict.Where(entry => predicate(entry.Key)).ToList() ) 
{
  dict.Remove(entry.Key);
}

and replace with just

foreach(var entry in dict)
{
    if (predicate(entry.Key)   // or test Key and Value
           dict.Remove(entry);
}

which is half as much code, half the complexity, and most importantly does not allocate.

It might take a Roslyn analyzer to find these.

@MarcoRossignoli any interest in taking a look?

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-MetaenhancementProduct code improvement that does NOT require public API changes/additionsgood first issueIssue should be easy to implement, good for first-time contributorshelp wanted[up-for-grabs] Good issue for external contributors

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions