简体   繁体   中英

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

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.

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.

ps 在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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