Efficient way to remove items from dictionary

2019-07-17 18:33发布

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.

3条回答
劫难
2楼-- · 2019-07-17 18:44

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.

查看更多
Fickle 薄情
3楼-- · 2019-07-17 18:50

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

查看更多
爷、活的狠高调
4楼-- · 2019-07-17 18:58

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. enter image description here

查看更多
登录 后发表回答