Remove Item in Dictionary based on Value

前端 未结 6 2026
长情又很酷
长情又很酷 2020-11-30 05:37

I have a Dictionary.

I need to look within that dictionary to see if a value exists based on input from somewhere else and if it e

6条回答
  •  没有蜡笔的小新
    2020-11-30 06:13

    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.

提交回复
热议问题