我有这样的字典:
Dictionary<KeyValuePair<int, string>, OperationType> clickedList;
其中OperationType是枚举{下载,安装,删除,启用}
我有另一个KeyValuePair列表,如下所示:
toRemove = machine.Array
.Select(x =>
new KeyValuePair<int, string>((int)x.MachineID, x.PackageID))
.ToList();
我需要做以下事情:
这样做有好办法吗?我该怎么做?
答案 0 :(得分:2)
我认为最有效的方法是使用HashSet&gt;存储应该从字典中删除的所有密钥 - 尽管此解决方案不使用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);
}
我相信上面的内容可能是删除元素的最有效方法,因为它在字典中的键数是线性的。