我有一个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:
收集被修改; 枚举操作可能无法执行.
我相信这可能是一个简单的方法,但我没有立即看到它.
您可以使用Enumerable.Except查找字典中没有的键:
foreach (var key in MyDictionary.Keys.Except(AllowedList).ToList())
MyDictionary.Remove(key);
Run Code Online (Sandbox Code Playgroud)
在ToList()创建差集的一个新的列表,防止异常.