gpt4 book ai didi

c#-4.0 - 给定要删除的键列表,从字典中删除键值对

转载 作者:行者123 更新时间:2023-12-04 17:24:22 25 4
gpt4 key购买 nike

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

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

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

foreach (string key in MyDictionary.Keys)
{
if (!AllowedList.Contains(key)) MyDictionary.Remove(key);
}

然而,我遇到了 InvalidOperationException :

Collection was modified; enumeration operation may not execute.



我确定可能有一个简单的方法来解决这个问题,但我没有立即看到它。

最佳答案

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

foreach (var key in MyDictionary.Keys.Except(AllowedList).ToList())
MyDictionary.Remove(key);
ToList()创 build 置差异的新列表并防止异常。

关于c#-4.0 - 给定要删除的键列表,从字典中删除键值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12807150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com