Remove Item in Dictionary based on Value

111,230

Solution 1

Are you trying to remove a single value or all matching values?

If you are trying to remove a single value, how do you define the value you wish to remove?

The reason you don't get a key back when querying on values is because the dictionary could contain multiple keys paired with the specified value.

If you wish to remove all matching instances of the same value, you can do this:

foreach(var item in dic.Where(kvp => kvp.Value == value).ToList())
{
    dic.Remove(item.Key);
}

And if you wish to remove the first matching instance, you can query to find the first item and just remove that:

var item = dic.First(kvp => kvp.Value == value);

dic.Remove(item.Key);

Note: The ToList() call is necessary to copy the values to a new collection. If the call is not made, the loop will be modifying the collection it is iterating over, causing an exception to be thrown on the next attempt to iterate after the first value is removed.

Solution 2

Dictionary<string, string> source
//
//functional programming - do not modify state - only create new state
Dictionary<string, string> result = source
  .Where(kvp => string.Compare(kvp.Value, "two", true) != 0)
  .ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
//
// or you could modify state
List<string> keys = source
  .Where(kvp => string.Compare(kvp.Value, "two", true) == 0)
  .Select(kvp => kvp.Key)
  .ToList();

foreach(string theKey in keys)
{
  source.Remove(theKey);
}

Solution 3

Loop through the dictionary to find the index and then remove it.

Solution 4

Here is a method you can use:

    public static void RemoveAllByValue<K, V>(this Dictionary<K, V> dictionary, V value)
    {
        foreach (var key in dictionary.Where(
                kvp => EqualityComparer<V>.Default.Equals(kvp.Value, value)).
                Select(x => x.Key).ToArray())
            dictionary.Remove(key);
    }
Share:
111,230
Jon
Author by

Jon

Updated on July 08, 2022

Comments

  • Jon
    Jon almost 2 years

    I have a Dictionary<string, string>.

    I need to look within that dictionary to see if a value exists based on input from somewhere else and if it exists remove it.

    ContainsValue just says true/false and not the index or key of that item.

    Help!

    Thanks

    EDIT: Just found this - what do you think?

    var key = (from k in dic where string.Compare(k.Value, "two", true) ==
    0 select k.Key).FirstOrDefault();
    

    EDIT 2: I also just knocked this up which might work

    foreach (KeyValuePair<string, string> kvp in myDic)
    {
        if (myList.Any(x => x.Id == kvp.Value))
            myDic.Remove(kvp.Key);
    }