views:

338

answers:

4

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

loop through the dictionary to find index and then remove it

Xinus
A: 

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(kvp in dic.Where(kvp.Value == value).ToDictionary())
{
    dic.Remove(kvp.Key);
}

And if you wish to remove the first matching instance, you can add a break to exit after the first match:

foreach(kvp in dic.Where(kvp.Value == value).ToDictionary())
{
    dic.Remove(kvp.Key);
    break;
}
Programming Hero
A: 
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);
}
David B
A: 

From the coment suggestions I enumerated the list and run the LINQ to find the key if it exists and then just call remove from my dictionary without concern

Jon