在给定要删除的键列表的情况下从字典中删除键,值对

use*_*753 5 dictionary c#-4.0

我有一个List<string> AllowedList和一个Dictionary<string,List<string>> MyDictionary.

对于字典中的每个键,我想检查它是否在AllowedList,如果不是我想从字典中删除键和值.

我直觉地尝试了这个似乎是我想要的东西:

foreach (string key in MyDictionary.Keys)
{
    if (!AllowedList.Contains(key)) MyDictionary.Remove(key);
}
Run Code Online (Sandbox Code Playgroud)

但是,我遇到了一个InvalidOperationException:

收集被修改; 枚举操作可能无法执行.

我相信这可能是一个简单的方法,但我没有立即看到它.

Tim*_*ter 9

您可以使用Enumerable.Except查找字典中没有的键:

foreach (var key in MyDictionary.Keys.Except(AllowedList).ToList())
    MyDictionary.Remove(key);
Run Code Online (Sandbox Code Playgroud)

ToList()创建差集的一个新的列表,防止异常.

  • Seismoid的解决方案也是有效的.不过,我确实喜欢这个linq设置差异的建议. (2认同)