简体   繁体   English

一次从字典中删除多个项目

[英]Remove multiple items from Dictionary at once

I have a dictionary like so: 我有这样的字典:

Dictionary<KeyValuePair<int, string>, OperationType> clickedList;

where OperationType is an Enum { Download, Install, Remove, Enable } 其中OperationType是枚举{下载,安装,删除,启用}

I have another KeyValuePair list like so: 我有另一个像这样的KeyValuePair列表:

toRemove = machine.Array
                  .Select(x => 
                      new KeyValuePair<int, string>((int)x.MachineID, x.PackageID))
                  .ToList();

I need to do the following: 我需要执行以下操作:

  1. Remove all items from clickedList that exist in toRemove and OperationType != "Remove" clickedList中删除toRemoveOperationType中存在的所有项目!=“ Remove”
  2. Remove all items from clickedList that have OperationType = "Remove" and DO NOT exist in toRemove list. clickedList中删除所有具有OperationType =“ Remove”并且不存在于toRemove列表中的项目。

Is there a good way of doing this? 有这样做的好方法吗? How would I do it? 我该怎么办?

I would think that the most efficient way to do that would be to use a HashSet> to store all the keys that should actually be removed from the dictionary - although this solution doesn't use linq: 我认为最有效的方法是使用HashSet>存储实际上应从字典中删除的所有键-尽管此解决方案不使用linq:

toRemove = machine.Array
              .Select(x => 
                  new KeyValuePair<int, string>((int)x.MachineID, x.PackageID))
              .ToList();

// create a hash set and initially put all the elements from toRemove in the set
var r = new HashSet<KeyValuePair<int, string>>(toRemove);

// go over each element in the clickedList
//    and check whether it actually needs to be removed
foreach(var kvp in clickedList.Keys)      // O(n);  n = # of keys/elem. in dictionary
{
    if(kvp.Value == OperationType.Remove)
    {
       if(r.Contains(kvp.Key)             // O(1)
          r.Remove(kvp.Key);              //    (1)
       else
          r.Add(kvp.Key);                 //   O(1)
    }
}

foreach(var key in r)                     // O(m); m = # of keys to be removed 
{
    clickedList.Remove(key);
}

I believe the above is probably the most efficient way of removing the elements since it's linear in the number of keys in the dictionary. 我相信以上内容可能是删除元素的最有效方法,因为它在字典中的键数上是线性的。

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

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