Remove Item in Dictionary based on Value

前端 未结 6 2023
长情又很酷
长情又很酷 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:59

    Dictionary source
    //
    //functional programming - do not modify state - only create new state
    Dictionary result = source
      .Where(kvp => string.Compare(kvp.Value, "two", true) != 0)
      .ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
    //
    // or you could modify state
    List keys = source
      .Where(kvp => string.Compare(kvp.Value, "two", true) == 0)
      .Select(kvp => kvp.Key)
      .ToList();
    
    foreach(string theKey in keys)
    {
      source.Remove(theKey);
    }
    

提交回复
热议问题