Remove Item in Dictionary based on Value

C#.NetLinqDictionary

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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 - C#

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 - C#

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

Solution 4 - C#

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

Solution 5 - C#

You can use the following as extension method

 public static void RemoveByValue<T,T1>(this Dictionary<T,T1> src , T1 Value)
    {
        foreach (var item in src.Where(kvp => kvp.Value.Equals( Value)).ToList())
        {
            src.Remove(item.Key);
        }
    }

Solution 6 - C#

In my case I use this

  var key=dict.FirstOrDefault(m => m.Value == s).Key;
            dict.Remove(key);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJonView Question on Stackoverflow
Solution 1 - C#Paul TurnerView Answer on Stackoverflow
Solution 2 - C#Amy BView Answer on Stackoverflow
Solution 3 - C#XinusView Answer on Stackoverflow
Solution 4 - C#ezolotkoView Answer on Stackoverflow
Solution 5 - C#shoushouleb86View Answer on Stackoverflow
Solution 6 - C#Jahongir MurtozayevView Answer on Stackoverflow