Remove Item in Dictionary based on Value

前端 未结 6 2016
长情又很酷
长情又很酷 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 05:58

    In my case I use this

      var key=dict.FirstOrDefault(m => m.Value == s).Key;
                dict.Remove(key);
    
    0 讨论(0)
  • 2020-11-30 05:59
    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);
    }
    
    0 讨论(0)
  • 2020-11-30 06:00

    Here is a method you can use:

        public static void RemoveAllByValue<K, V>(this Dictionary<K, V> dictionary, V value)
        {
            foreach (var key in dictionary.Where(
                    kvp => EqualityComparer<V>.Default.Equals(kvp.Value, value)).
                    Select(x => x.Key).ToArray())
                dictionary.Remove(key);
        }
    
    0 讨论(0)
  • 2020-11-30 06:11

    Loop through the dictionary to find the index and then remove it.

    0 讨论(0)
  • 2020-11-30 06:12

    You can use the following as extension method

     public static void RemoveByValue<T,T1>(this Dictionary<T,T1> src , T1 Value)
        {
            foreach (var item in src.Where(kvp => kvp.Value.Equals( Value)).ToList())
            {
                src.Remove(item.Key);
            }
        }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题