I have a Dictionary and a List of keys to remove from the dictionary. This is my implementation right now:
var keys = (from entry in etimes
where Convert.ToInt64(entry.Value) < Convert.ToInt64(stime)
select entry.Key).ToList();
foreach (var key in keys)
{
etimes.Remove(key);
count--;
}
Is there something I can do the eliminate the foreach loop?
This statement simply filters the dictionary using the LINQ
Wherefunction to select which items to keep rather than those to remove (which then requires further code, as you showed). TheToDictionaryconverts thweIEnumerable<KeyValuePair<TKey, TValue>>to the desireDictionary<TKey, TValue>type, and is at least quite simple, if not terribly elegant or efficient due to the need to specify the two lambda expressions to select the key and value from aKeyValuePair(and then creating a new dictionary). Saying this, I don’t really see it as a problem, especially if the dictionary is small and/or number of items being removed is large.