在循环中检查不同字典中单词的值
本文关键字:单词 字典 循环 检查 | 更新日期: 2023-09-27 17:49:19
我有两个字典,我在其中一个字典中查找,只有当相同键在另一个字典中的值大于5时,我才想做数学运算。
如何正确使用if语句?
foreach (var word in dict1)
{
temp = word.Value;
// something like this:
if (temp in dict2 > 5)
{
A *= temp;
}
else
{
// do nothing
}
}
如果dict1和dict2都使用Dictionary:
foreach(var word in dict1.Where(w=>dict2.ContainsKey(w.Key) && dict2[w.Key]>5))
{
//dowork
}
这只迭代dict1中dict2中值大于5的项,并做一些操作。
编辑:添加dic2 . containskey (w.p key) check in Where子句,因为dic2可能不包含dict1中的键
类似这样的东西,加上更好的错误处理,应该可以做到这一点。这里假设word.key
是用来查找dict2
中的值的正确键。
if (dict2[word.key] > 5)
{
A *= temp;
}
正如ASh所说,这很简单:
if(dict2[word.Key]>5){}
使用前面提到的重链接路由
dict1.Keys
.Intersect(dict2.Keys) // We only care about keys in both dictionaries
.Where(k => dict2[key] > 5)// We only care when the value in dict2 is greater than 5
.Select(l => dict1[k]) // Get the values from dict1