Multiple Defered WHERE clause expressions in LINQ to SQL

我是研究僧i 提交于 2020-01-04 14:26:24

问题


Maybe a simple question, I'm trying to get a result from a table where the Name column contains all of an array of search terms. I'm creating a query and looping through my search strings, each time assigning the query = query.Where(...);. It appears that only the last term is being used, I supposed because I am attempting to restrict the same field each time. If I call .ToArray().AsQueryable() with each iteration I can get the cumlative restrinction behavior I'm looking for, but it there an easy way to do this using defered operators only?

Thanks!


回答1:


If you're doing something like:

foreach (int foo in myFooArray)
{
  query = query.where(x => x.foo == foo);
}

...then it will only use the last one since each where criteria will contain a reference to the 'foo' loop variable.

If this is what you're doing, change it to:

foreach (int foo in myFooArray)
{
  int localFoo = foo;
  query = query.where(x => x.foo == localFoo);
}

...and everything should be fine again.

If this is not what is happening, please provide a code sample of what you're doing...



来源:https://stackoverflow.com/questions/1280871/multiple-defered-where-clause-expressions-in-linq-to-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!