简体   繁体   English

linq to sql中的奇怪行为

[英]strange behavior in linq to sql

I'm trying to find all element that contains all words in a phrase after geting them from database: 我试图从数据库中找到包含短语中所有单词的所有元素:

string text = "ab cd 23";//the element prop2 must have all 3 word regardless their order
var q = from c in db.myTable
where c.Prop1 == "value"
select c;
string[] strings = text.Split(' ');
foreach(string word in strings)
{
       int cnt = q.Count();//first time cnt = 1500 which is correct 
       q = q.Where(c => c.Prop2.Contains(word));// Prop2 is a string
       cnt = q.Count();//first time cnt = 460
}

everything is alright till this: 一切顺利,直到这个:

foreach(string word in strings)// second time
{
       int cnt = q.Count();//second time cnt = 14 ??
       q = q.Where(c => c.Prop2.Contains(word));
       cnt = q.Count();//first time cnt = 2
}

without doing anything at the second loop the element count changes furthermore this should return only element with all the words but it return element with just the last one and the third loop is useless changes nothing 在第二个循环中没有做任何事情,元素计数发生了变化,这应该只返回带有所有单词的元素但是它返回的元素只有最后一个而第三个循环是无用的更改没有

I'm sorry for the long Q but I'm new to linq 我很抱歉Q长,但我是linq的新手

I think this may be the dreaded "modified closure" error. 我认为这可能是可怕的“修改后的闭包”错误。 Create a temporary copy of the word loop variable, and use it instead in your queries. 创建word循环变量的临时副本,并在查询中使用它。

foreach(string word in strings) {
    var tmp = word;
    int cnt = q.Count();
    q = q.Where(c => c.Prop2.Contains(tmp));
    cnt = q.Count();//first time cnt = 460
}

You should avoid using loop variables in LINQ expressions, unless you "materialize" them right away (ie call ToList() , ToArray , First() , SingleOrDefault , etc.) When you need to use the value of your loop variable, make a temporary copy. 你应该避免在LINQ表达式中使用循环变量,除非你立即“实现”它们(即调用ToList()ToArrayFirst()SingleOrDefault等)当你需要使用循环变量的值时,做一个临时副本。 The reason is that LINQ defers execution of your query, so when by the time the query gets executed the value of the loop variable has changed, your results will change unexpectedly. 原因是LINQ延迟了查询的执行,所以当查询执行时,循环变量的值已经改变,结果会意外地改变。

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

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