How to delete entries from a dictionary using the value

后端 未结 5 891
广开言路
广开言路 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);
    }
    

提交回复
热议问题