如何从字典中使用的值删除条目条目、字典

2023-09-03 02:52:27 作者:怪°

我有一本字典集合作为bleow:

I have a dictionary collection as bleow:

mydic.addvalue(key1, val1)
mydic.addvalue(key2, val1)
mydic.addvalue(key3, val1)
mydic.addvalue(key4, val2)
mydic.addvalue(key5, val2)

从上面的词典我要删除所有条目,其中value ==VAL1,这样的结果将只有以下项:

From the above dictionary I want to delete all the entries where value == "val1", so that the result would have only following entry:

mydic.addvalue(key4, val2)
mydic.addvalue(key5, val2)

我的VB源$ C ​​$,C是VS2008和有针对性的为3.5

My VB source code is on VS2008 and targeted for 3.5

推荐答案

一个基于评论用户非LINQ的答案。

A non-LINQ answer based on a comment by the user.

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);
    }
}

实例:

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.