更新时间:2023-11-26 17:59:04
这取决于你需要如何执行。如果您可以接受 O(N)
的表现,您可以执行以下操作:
It depends on how you need it to perform. If you can accept O(N)
performance, you could just do something like:
foreach(var pair in clients) {
if(pair.Value == expected) {
clients.Remove(pair.Key);
break;
}
}
然而,如果你需要更快,你需要两个字典 - 一个与另一个相反(即由实例锁定)。因此,添加时,您可以:
However, if you need faster you would need two dictionaries - one the reverse of the other (i.e. keyed by the instances). So when adding, you would do:
clientsByKey.Add(key, value);
clientsByValue.Add(value, key);
,以便您可以执行(按值移除):
so you can do (to remove-by-value):
string key;
if(clientsByValue.TryGetValue(value, out key)) {
clientsByValue.Remove(value);
clientsByKey.Remove(key);
}
或类似(按键删除):
Foo value;
if(clientsByKey.TryGetValue(key, out value)) {
clientsByValue.Remove(value);
clientsByKey.Remove(key);
}