Remove all items matching the condition in the IDictionary

I am trying to remove all elements in an IDictionary that match a condition.

eg. IDictionary contains a set of keys and corresponding values ​​(say, 80 objects). Keys are strings, values ​​can be of different types (I think, extracting metadata from a wtv file using directshow).

Some of the keys contain thumb text, for example. thumbsize, startthumbdate etc. I want to remove all objects from an IDictionary whose keys contain the word thumb.

The only thing I see here is to manually specify each key name using the .Remove method.

Is there a way to get all the objects whose keys contain the word thumb and they remove them from the IDictionary.

The code is as follows:

IDictionary sourceAttrs = editor.GetAttributes();

GetAttributes is defined as:

public abstract IDictionary GetAttributes();

GetAttributes, IDictionary, , . (, HashTable)

UPDATE: Tim:

sourceAttrs = sourceAttrs.Keys.Cast<string>()
                 .Where(key => key.IndexOf("thumb", StringComparison.CurrentCultureIgnoreCase) == -1)
                 .ToDictionary(key => key, key => sourceAttrs[key]);
+4
2

, , .

LINQ, , :

dict = dict
  .Where(kv => !kv.Key.Contains("thumb"))
  .ToDictionary(kv => kv.Key, kv => kv.Value);

, IndexOf:

dict = dict
  .Where(kv => kv.Key.IndexOf("thumb", StringComparison.CurrentCultureIgnoreCase) == -1)
  .ToDictionary(kv => kv.Key, kv => kv.Value);

:

, HashTable, LINQ , , string, :

// sample IDictionary with an old Hashtable
System.Collections.IDictionary sourceAttrs = new System.Collections.Hashtable
{ 
    {"athumB", "foo1"},
    {"other", "foo2"}
};

Dictionary<string, object> newGenericDict = sourceAttrs.Keys.Cast<string>()
    .Where(key => !key.Contains("thumb"))
    .ToDictionary(key => key, key => sourceAttrs[key]);

, , Dictionary, as:

var dict = sourceAttrs as Dictionary<string, object>;

, .

+6

, , LINQ:

dict
  .Keys
  .Where(p => p.Contains("thumb"))
  .ToList
  .ForEach(p => dict.Remove(p);

, , : , , , .

, , .

0

Source: https://habr.com/ru/post/1540074/


All Articles