An effective way to delete all entries in a dictionary below a specified value

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?

+3
3

, , , :

dic = dic.Where(kvp => kvp.Value > lowerBound).ToDictionary();

, foreach, .

, , , , . , . :

kvp => kvp.Value > lowerBound

, , "kvp", :

kvp.Value > lowerBound

=> "-", . LINQ, Func, - , . , .

-.

+13

.

foreach(var kvp in dic.Where(x => x.Value <= lowerBound).ToDictionary())
{
    dic.Remove(kvp.Key);
}
0
dic.Where(kvp.Value <= lowerBound)

replace

dic.Where(kvp1 => kvp1.Value <= lowerBound)
0
source

Source: https://habr.com/ru/post/1735075/


All Articles