Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use LINQ to "prune" a dictionary?

Tags:

c#

linq

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?

like image 487
scottm Avatar asked May 06 '09 17:05

scottm


1 Answers

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.

like image 168
Noldorin Avatar answered Nov 10 '22 00:11

Noldorin