Why*_*Why 2 c# generics collections dictionary visual-studio
标题本身应该清楚这个问题.我需要检查字典中是否存在某个项目,并将其从C#中的字典中删除.唯一的问题是,我必须只使用有价值的物品,而不是钥匙.
声明如下:
IDictionary<string, myCustomClassObject> clients = new IDictionary<string, myCustomClassObject>();
Run Code Online (Sandbox Code Playgroud)
现在我填写字典:
clients["key"] = myCustomClassObject1;
Run Code Online (Sandbox Code Playgroud)
现在我如何myCustomClassObject1从我的词典中找到并删除此项目.我只想使用值项而不是键
这是doabale ......如果是这样,请指导......问候
编辑:谢谢大家......得到了宝贵的意见......可能有一些想法......谢谢
这取决于你需要它如何执行.如果你能接受O(N)表演,你可以做以下事情:
foreach(var pair in clients) {
if(pair.Value == expected) {
clients.Remove(pair.Key);
break;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果你需要更快,你需要两个字典 - 一个与另一个相反(即由实例键控).所以在添加时,您会这样做:
clientsByKey.Add(key, value);
clientsByValue.Add(value, key);
Run Code Online (Sandbox Code Playgroud)
所以你可以做(按值删除):
string key;
if(clientsByValue.TryGetValue(value, out key)) {
clientsByValue.Remove(value);
clientsByKey.Remove(key);
}
Run Code Online (Sandbox Code Playgroud)
或类似地(按键移除):
Foo value;
if(clientsByKey.TryGetValue(key, out value)) {
clientsByValue.Remove(value);
clientsByKey.Remove(key);
}
Run Code Online (Sandbox Code Playgroud)