Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete entries from a dictionary using the value

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)

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)

My VB source code is on VS2008 and targeted for 3.5

like image 541
user350233 Avatar asked Jun 07 '10 18:06

user350233


2 Answers

You first need to find all keys for which the associated value is 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);
}
like image 50
dtb Avatar answered Oct 29 '22 02:10

dtb


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

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.

like image 34
Anthony Pegram Avatar answered Oct 29 '22 02:10

Anthony Pegram