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.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
Linq is also using loops. Linq can just help you to find what you want to remove.
This should be efficient since it uses
ContainsKey
which is a O(1) operation, for everyKeyValuePair
in the secondDictionary
.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.The appropriate way to do this would be:
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 callContainsKey
before calling remove (this will save you an extra table lookup for each item).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:
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.