score:136

Accepted answer

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.

score:-2

in my case i use this

  var key=dict.firstordefault(m => m.value == s).key;
            dict.remove(key);

score:0

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

score:1

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

score:2

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

score:9

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

Related Query

More Query from same tag