So you want to remove all entries where the key contains a sub-string.
You can use LINQ by keeping all that does not contain it:
dict = dict
.Where(kv => !kv.Key.Contains("thumb"))
.ToDictionary(kv => kv.Key, kv => kv.Value);
If you want a case-insensitive comparison you can use IndexOf
:
dict = dict
.Where(kv => kv.Key.IndexOf("thumb", StringComparison.CurrentCultureIgnoreCase) == -1)
.ToDictionary(kv => kv.Key, kv => kv.Value);
Update according to your non-generic edit:
If it's a non-generic dictionary like a HashTable
you cannot use LINQ directly, but if you know that the key is a string
you could use following query:
// 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]);
But maybe it's actually a generic Dictionary
, you can try-cast with the as
operator:
var dict = sourceAttrs as Dictionary<string, object>;
It's null if the cast didn't work.