Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing values from a dictionary using loop

Tags:

c#

dictionary

I have procedure where I want to remove values from a dictionary based on a certain condition(comparing the key values to another dictionary)

In the foreach loop I am however not allowed to modify the dictionary.

Is there perhaps a better way of doing this?

The key values are string,

foreach (var archive in dictArchivedTitles)
{
       foreach (var kvp in dictAllTheFiles)
       {
           if (kvp.Key == archive.Key)
           {
               dictAllTheFiles.Remove(kvp.Key);
           }
       }
  }
like image 969
Arianule Avatar asked Dec 17 '25 19:12

Arianule


1 Answers

You can do the following.

foreach (var archive in dictArchivedTitles)
{
    if(dictAllTheFiles.ContainsKey(archive.Key)
        dictAllTheFiles.Remove(archive.Key);
}
like image 58
juharr Avatar answered Dec 20 '25 07:12

juharr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!