I need to delete all entries in the dictionary according to the specified lower bound.
My current solution is this:
List<string> keys = new List<string>();
foreach (KeyValuePair<string, int> kvp in dic)
{
if (kvp.Value < lowerBound)
keys.Add(kvp.Key);
}
foreach (string key in keys)
dic.Remove(key);
However, it is quite expensive, especially since the size of the dictionary is quite large.
I saw the LINQ solution like:
foreach(var kvp in dic.Where(kvp.Value <= lowerBound).ToDictionary())
{
dic.Remove(kvp.Key);
}
which I suppose to be better, since this is only 1 foreach, but I get:
The name 'kvp' does not exist in the current context
Type arguments to the 'System.Linq.Enumerable.Where (System.Collections.Generic.IEnumerable, System.Func)' method cannot be taken out of use. Try specifying type arguments explicitly.
I admit that I don’t know anything about LINQ, so there are ideas how to make this second solution work or better?