问题描述
我有两个字典dict1和dict2,我想使用dict2的键从dict1中删除存在于dict2中的项.除了使用dict而不是遍历dict2并使用"ContainsKey"方法外,还有其他方法,例如使用linq.
I have two dictionaries dict1 and dict2, I would like to remove items from dict1 which are present in dict2 using its key. Instead of looping through dict2 and using "ContainsKey" method, ia there any other approach like using linq.
推荐答案
执行此操作的合适方法是:
The appropriate way to do this would be:
foreach(var key in dic2.Keys)
{
dic1.Remove(key);
}
LINQ代表语言集成 Query .它用于对数据执行查询.查询不会改变基础结构.由于您要做的是更改查询LINQ之一,因此这不是一种合适的工具.
LINQ stands for Language Integrated Query. It is for performing queries on data. Queries do not mutate the underlying structures. Since what you want to do is to mutate one of the queries LINQ is not an appropriate tool.
还要注意,Remove
返回一个布尔值,指示它是否实际删除了密钥.它不会引发异常.您无需在调用remove之前调用ContainsKey
(这将为您节省每个项目的额外表查找时间).
Also note that Remove
returns a boolean indicating whether or not it actually removed the key. It doesn't throw an exception. You don't need to call ContainsKey
before calling remove (this will save you an extra table lookup for each item).
这篇关于从字典中删除项目的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!