检查项目是否存在于字典中,并从C#中的字典中删除它 [英] Check if an item exist in the dictionary and remove it from the dictionary in C#
问题描述
问题应该从标题本身清楚。我需要检查一个项目是否存在于字典中,并从C#中的字典中删除它。唯一的办法是,我只能使用值项而不是键。
The question should be clear from the title itself. I need to check if an item exist in the dictionary and remove it from the dictionary in C#. The only catch is that i have to do this using only the value item and not the key.
声明如下:
IDictionary<string, myCustomClassObject> clients = new IDictionary<string, myCustomClassObject>();
现在我通过以下方式填写字典:
Now i fill in the dictionary by:
clients["key"] = myCustomClassObject1;
现在如何找到并删除此项 myCustomClassObject1
从我的词典。我只想使用值项目而不是键
Now how can i find and remove this item myCustomClassObject1
from my Dictionary. I only want to use the value item and not the key
这是doabale ...如果是这样,请指导...
Is this doabale...if so please guide... regards
编辑:谢谢大家....有价值的意见...可能有一些想法...感谢
Thank you all....got valuable comments...probably have some thinking to do ...thanks
推荐答案
这取决于你需要如何执行。如果您可以接受 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);
}
这篇关于检查项目是否存在于字典中,并从C#中的字典中删除它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!