Priya
Priya

Reputation: 69

Delete all the keys from the dictionary if the value matches for more than one key

I have a dictionary

private readonly Dictionary<string, WebResponse> _myDictionary;

Lets assume I have 10 values in the dictionary currently. I can able to add some values into it also I can delete the values based on the key present in the dictionary similar to below.

Remove:

_myDictionary.Remove(Key); 

where key is a string variable.

Is that possible to delete more than one key at a time if the values matches for more than one key. I have keys like {KAAR1, KAAR2, KAAR3, ABCDEF}. Now I need to delete all the keys which contains "KAAR". Is that possible to do.

Kindly help.

Upvotes: 4

Views: 1025

Answers (3)

Battle
Battle

Reputation: 816

I expanded the answer of @Enigmativity to provide two generic versions as extension methods.

/// <summary> Removes all duplicate values after the first occurrence. </summary>
public static void RemoveDuplicates<T, V> (this Dictionary<T, V> dict)
{
    List<V> L = new List<V> ();
    int i = 0;
    while (i < dict.Count)
    {
        KeyValuePair<T, V> p = dict.ElementAt (i);
        if (!L.Contains (p.Value))
        {
            L.Add (p.Value);
            i++;
        }
        else
        {
            dict.Remove (p.Key);
        }
    }
}

With a dictionary of values (ignoring keys): 0, 1, 2, 3, 5, 1, 2, 4, 5. Result: 0, 1, 2, 3, 5, 4.

/// <summary> Removes all values which have any duplicates. </summary>
public static void RemoveAllDuplicates<T, V> (this Dictionary<T, V> dict)
{
    List<V> L = new List<V> ();
    int i = 0;
    while (i < dict.Count)
    {
        KeyValuePair<T, V> p = dict.ElementAt (i);
        if (!L.Contains (p.Value))
        {
            L.Add (p.Value);
            i++;
        }
        else
        {
            dict.Where (j => Equals (j.Value, p.Value)).ToList ().ForEach (j => dict.Remove (j.Key));
        }
    }
}

With a dictionary of values (ignoring keys): 0, 1, 2, 3, 5, 1, 2, 4, 5. Result: 3, 4.

The methods are optimized to prevent multiple executions of the .Where operation (otherwise each duplicate would have n executions of it, where all after the first one is obsolete). Code is tested and working.

Upvotes: 0

Priya
Priya

Reputation: 69

Below is the answer given by the user @Enigmavitivity!! Added as seprate answer to mark as a correct one.

_myDictionary.Where(x => x.Key.Contains("KAAR")).ToList().ForEach(kvp => _myDictionary.Remove(kvp.Key));

Upvotes: 0

Enigmativity
Enigmativity

Reputation: 117027

Try this:

_myDictionary
    .Where(x => x.Key.Contains("KAAR"))
    .ToList()
    .ForEach(kvp => _myDictionary.Remove(kvp.Key));

Upvotes: 9

Related Questions