Andy
Andy

Reputation: 13527

Remove multiple keys with same value data from dictionary in C# using Linq

I know there has to be a better way to do this... maybe with LINQ? If I remove a value, it invalidates the iterator which is why I have this inside of an infinite loop which starts the process all over again. I'm looking for a way to do this that is easier to read, maintain and ultimately much faster. Here's what I got:

Dictionary<string, string> Channels = //...;
while (true)
{
    var bFound = false;
    foreach(var c in Channels)
    {
        if(c.Value == version)
        {
            Channels.Remove(c.Key);
            bFound = true;
            break;
        }
    }
    if (!bFound) { break; }
}

Thanks for any help in optimizing this routine.

Upvotes: 1

Views: 1998

Answers (3)

CodeNotFound
CodeNotFound

Reputation: 23200

I'm looking for a way to do this that is easier to read, maintain and ultimately much faster

Just use the code below:

var keys = Channels.Keys.ToArray();
foreach(var key in keys)
{
    if(Channels[key] == version)
    {
        Channels.Remove(key);
    }
}

No LINQ needed for simplicity. We traverse the dictionary once for performance.

Upvotes: 3

Amy B
Amy B

Reputation: 110071

If you capture the matches before removing items from the dictionary, your enumerator will not be invalidated.

List<KeyValuePair<string, string>> matches = Channels
  .Where(kvp => kvp.Value == version)
  .ToList();

foreach(KeyValuePair<string, string> match in matches)
{
  Channels.Remove(match.Key);
}

Upvotes: 2

Harsh
Harsh

Reputation: 3751

Based on your example it appears you are removing based on comparison with version value.

Channels = Channels.Where(x=> x.Value != version)
              .ToDictionary(c => c.Key, c => c.Value);

Upvotes: 7

Related Questions