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?
var pruned = etimes.Where(entry => Convert.ToInt64(entry.Value) >=
Convert.ToInt64(stime)).ToDictionary(entry => entry.Key,
entry => entry.Value);
This statement simply filters the dictionary using the LINQ Where
function to select which items to keep rather than those to remove (which then requires further code, as you showed). The ToDictionary
converts thwe IEnumerable<KeyValuePair<TKey, TValue>>
to the desire Dictionary<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 a KeyValuePair
(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With