简体   繁体   English

从字典中删除项目的有效方法

[英]Efficient way to remove items from dictionary

I have two dictionaries dict1 and dict2, I would like to remove items from dict1 which are present in dict2 using its key. 我有两个词典dict1和dict2,我想从dict2中删除dict2中使用其键的项目。 Instead of looping through dict2 and using "ContainsKey" method, ia there any other approach like using linq. 而不是循环通过dict2并使用“ContainsKey”方法,我还有其他方法,比如使用linq。

The appropriate way to do this would be: 适当的方法是:

foreach(var key in dic2.Keys)
{
    dic1.Remove(key);
}

LINQ stands for Language Integrated Query . LINQ代表语言集成查询 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. 因为你想要做的是改变其中一个查询LINQ不是一个合适的工具。

Also note that Remove returns a boolean indicating whether or not it actually removed the key. 另请注意, Remove返回一个布尔值,指示它是否实际删除了该键。 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). 在调用remove之前,您不需要调用ContainsKey (这将为每个项目节省额外的表查找)。

Linq is also using loops. Linq也在使用循环。 Linq can just help you to find what you want to remove. Linq可以帮助您找到要删除的内容。

foreach (var kv in dict2.Where(kv => dict1.ContainsKey(kv.Key))) 
    dict1.Remove(kv.Key);

This should be efficient since it uses ContainsKey which is a O(1) operation, for every KeyValuePair in the second Dictionary . 这应该是高效的,因为它对第二个Dictionary中的每个KeyValuePair使用ContainsKey ,这是一个O(1)操作。

http://msdn.microsoft.com/en-us/library/kabs04ac.aspx http://msdn.microsoft.com/en-us/library/kabs04ac.aspx

Edit : Of course Servy's approach is better in general because you can use Dictionary.Remove even if the given key does not exist. 编辑 :当然,Servy的方法通常更好,因为即使给定的密钥不存在,您也可以使用Dictionary.Remove

As others mentioned, whether linq is the right tool for this job is debatable. 正如其他人所提到的,linq是否适合这项工作是值得商榷的。 However, if it has to be linq, I believe this is the apropriate solution: 但是,如果必须是linq,我相信这是合适的解决方案:

var dict1 = new Dictionary<int,double>();
var dict2 = new Dictionary<int,double>();

dict1 = dict1.Where(kv => !dict2.ContainsKey(kv.Key))
             .ToDictionary(kv => kv.Key, kv=>kv.Value);

This does not remove the keys from the existing dictionary, instead it generates a new dictionary with only the required keys. 这不会从现有字典中删除键,而是生成仅包含所需键的新字典。

This might actually be faster if most of the keys have to be removed. 如果必须删除大多数密钥,这实际上可能会更快。

ps PS 在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM