[英]How to delete entries from a dictionary using the value
I have a dictionary collection as bleow: 我有一个词典集合作为bleow:
mydic.addvalue(key1, val1)
mydic.addvalue(key2, val1)
mydic.addvalue(key3, val1)
mydic.addvalue(key4, val2)
mydic.addvalue(key5, val2)
From the above dictionary I want to delete all the entries where value == "val1", so that the result would have only following entry: 从上面的字典我想删除值==“val1”的所有条目,以便结果只有以下条目:
mydic.addvalue(key4, val2)
mydic.addvalue(key5, val2)
My VB source code is on VS2008 and targeted for 3.5 我的VB源代码在VS2008上,目标是3.5
You first need to find all keys for which the associated value is val1
: 首先需要找到关联值为
val1
所有键:
var keysToRemove = mydic.Where(kvp => kvp.Value == val1)
.Select(kvp => kvp.Key)
.ToArray();
Then you can remove each of those keys: 然后你可以删除每个键:
foreach (var key in keysToRemove)
{
mydic.Remove(key);
}
A non-LINQ answer based on a comment by the user. 基于用户评论的非LINQ答案。
private static void RemoveByValue<TKey,TValue>(Dictionary<TKey, TValue> dictionary, TValue someValue)
{
List<TKey> itemsToRemove = new List<TKey>();
foreach (var pair in dictionary)
{
if (pair.Value.Equals(someValue))
itemsToRemove.Add(pair.Key);
}
foreach (TKey item in itemsToRemove)
{
dictionary.Remove(item);
}
}
Example usage: 用法示例:
Dictionary<int, string> dictionary = new Dictionary<int, string>();
dictionary.Add(1, "foo");
dictionary.Add(2, "foo");
dictionary.Add(3, "bar");
string someValue = "foo";
RemoveByValue(dictionary, someValue);
Same caveat as with the other answers: if your value determines equality by reference, you'll need to do extra work. 与其他答案一样的警告:如果您的值通过引用确定相等性,则您需要做额外的工作。 This is just a base.
这只是一个基础。
You can also use 你也可以使用
var x= (from k in mydic
where k.Value != val1
select k).ToDictionary(k=>k.key);
x will not have any of the val1's x将不具有任何val1
foreach(var key in dict.AllKeys.ToArray())
{
if(...)
//remove key or something
}
The answer it's old but this is how I do the same thing without create another Dictionary. 它的答案很古老,但这就是我如何在不创建另一个词典的情况下做同样的事情。
foreach (KeyValuePair<TKey, TValue> x in MyDic) {
if (x.Value == "val1"))
{ MyDic.Remove(x.Key); }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.