简体   繁体   English

删除字典中低于指定值的所有条目的有效方法

[英]Efficient way to remove all entries in a dictionary lower than a specified value

I need to remove all entries in a dictionary accordingly to a 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 this is rather expensive, especially since the size of the dictionary is rather large. 然而,这相当昂贵,特别是因为字典的大小相当大。

I've seen a LINQ solution like: 我见过LINQ解决方案,如:

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

which I assume to be better since it's just 1 foreach, but I'm getting: 我认为它更好,因为它只是一个foreach,但我得到:

The name 'kvp' does not exist in the current context 当前上下文中不存在名称“kvp”

The type arguments for method 'System.Linq.Enumerable.Where(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. 无法从用法中推断出方法'System.Linq.Enumerable.Where(System.Collections.Generic.IEnumerable,System.Func)'的类型参数。 Try specifying the type arguments explicitly. 尝试显式指定类型参数。

I admit I don't know anything about LINQ so any ideas how to make this 2nd solution work, or a better one? 我承认我对LINQ一无所知,所以任何想法如何使这个第二个解决方案工作,或更好的?

Don't remove them explicitly, reassign the dictionary using only the values that are above that lower bound instead: 不要显式删除它们,只使用高于该下限的值重新分配字典:

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

That way you can completely eliminate that foreach loop you've got in there. 这样你就可以完全消除你在那里的foreach循环。

Also, the reason you're getting that error is that you're not using the proper lambda syntax. 此外,您收到该错误的原因是您没有使用正确的lambda语法。 In fact, you're not using a lambda at all. 事实上,你根本就没有使用lambda。 The expression: 表达方式:

kvp => kvp.Value > lowerBound

Is shorthand for a method that takes one parameter, called "kvp", and returns the evaluation of the expression: 是一个带有一个参数的方法的简写,称为“kvp”,并返回表达式的求值:

kvp.Value > lowerBound

The => is called the "lambda operator", and it separates the parameter intake from the returned output. =>称为“lambda运算符”,它将参数值与返回的输出值分开。 Every LINQ method that takes a Func is asking for a delegate of some sort, typically expressed as a lambda expression for brevity. 每个接受Func的LINQ方法都要求某种类型的委托,通常表示为lambda表达式以简洁起见。 When you give it the lambda expression, the compiler will stop complaining. 当你给它lambda表达式时,编译器将停止抱怨。

Read this for more information on lambda expressions. 有关lambda表达式的更多信息,请阅读此内容

Try this. 尝试这个。

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

用。。。来代替

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM