内置于 foreach 循环的 Linq 查询总是从上次迭代中获取参数值 [英] Linq query built in foreach loop always takes parameter value from last iteration

查看:23
本文介绍了内置于 foreach 循环的 Linq 查询总是从上次迭代中获取参数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个关键字的列表.我通过他们 foreach 像这样构建我的 linq 查询(归结为消除代码噪音):

I have a List containing several keywords. I foreach through them building my linq query with them like so (boiled down to remove the code noise):

List<string> keys = FillKeys()
foreach (string key in keys){
    q = q.Where(c => c.Company.Name.Contains(key));
}

当我现在让我的键包含 2 个单独返回结果的键时,但永远不会一起出现(q 中的每个项目都是xyz"或123",永远不会是123"和xyz"),我仍然得到结果.结果集与它得到的最后一个字符串相同.

When I now make my keys contain 2 keys that return results seperatly, but can never occure together (every item in q is either "xyz" or "123", never "123" AND "xyz"), I still get results. The resultset is then the same as the last string it got to.

我查看了 linq 查询,它似乎创建了正确的 sql,但它将 @p1 和 @p2 替换为相同的(最后一次迭代的)值.

I had a look at the linq query and it appears it creates the correct sql, but it replaces @p1 AND @p2 both by the same (last itterated) value.

我做错了什么?

推荐答案

您在 lambda 表达式中重用了相同的变量 (key).

You're reusing the same variable (key) in your lambda expression.

查看我关于匿名方法的文章以了解更多信息详细信息,还有许多相关的 SO 问题:

See my article on anonymous methods for more details, and there are a number of related SO questions too:

简单的解决方法是先复制变量:

The simple fix is to copy the variable first:

List<string> keys = FillKeys()
foreach (string key in keys){
    string copy = key;
    q = q.Where(c => c.Company.Name.Contains(copy));
}

这篇关于内置于 foreach 循环的 Linq 查询总是从上次迭代中获取参数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆