How to delete entries from a dictionary using the value

后端 未结 5 887
广开言路
广开言路 2021-01-06 10:48

I have a dictionary collection as bleow:

mydic.addvalue(key1, val1)
mydic.addvalue(key2, val1)
mydic.addvalue(key3, val1)
mydic.addvalue(key4, val2)
mydic.ad         


        
相关标签:
5条回答
  • 2021-01-06 11:30

    You first need to find all keys for which the associated value is val1:

    var keysToRemove = mydic.Where(kvp => kvp.Value == val1)
                            .Select(kvp => kvp.Key)
                            .ToArray();
    

    Then you can remove each of those keys:

    foreach (var key in keysToRemove)
    {
        mydic.Remove(key);
    }
    
    0 讨论(0)
  • 2021-01-06 11:35

    You can also use

    var x= (from k in mydic
               where k.Value != val1
               select k).ToDictionary(k=>k.key);
    

    x will not have any of the val1's

    0 讨论(0)
  • 2021-01-06 11:39

    The answer it's old but this is how I do the same thing without create another Dictionary.

    foreach (KeyValuePair<TKey, TValue> x in MyDic) {
    
      if (x.Value == "val1")) 
      {  MyDic.Remove(x.Key); } 
    }
    
    0 讨论(0)
  • 2021-01-06 11:44

    A non-LINQ answer based on a comment by the user.

    private static void RemoveByValue<TKey,TValue>(Dictionary<TKey, TValue> dictionary, TValue someValue)
    {
        List<TKey> itemsToRemove = new List<TKey>();
    
        foreach (var pair in dictionary)
        {
            if (pair.Value.Equals(someValue))
                itemsToRemove.Add(pair.Key);
        }
    
        foreach (TKey item in itemsToRemove)
        {
            dictionary.Remove(item);
        }
    }
    

    Example usage:

    Dictionary<int, string> dictionary = new Dictionary<int, string>();
    dictionary.Add(1, "foo");
    dictionary.Add(2, "foo");
    dictionary.Add(3, "bar");
    string someValue = "foo";
    RemoveByValue(dictionary, someValue);
    

    Same caveat as with the other answers: if your value determines equality by reference, you'll need to do extra work. This is just a base.

    0 讨论(0)
  • 2021-01-06 11:44
    foreach(var key in dict.AllKeys.ToArray())
    {
        if(...)
            //remove key or something
    }
    
    0 讨论(0)
提交回复
热议问题