Efficient way to remove items from dictionary

放肆的年华 提交于 2019-12-11 00:23:37

问题


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.


回答1:


The appropriate way to do this would be:

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

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.

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).




回答2:


Linq is also using loops. Linq can just help you to find what you want to remove.

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.

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.




回答3:


As others mentioned, whether linq is the right tool for this job is debatable. However, if it has to be linq, I believe this is the apropriate solution:

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.

p.s.



来源:https://stackoverflow.com/questions/12320289/efficient-way-to-remove-items-from-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!