Paul
Paul

Reputation: 6218

Multiple Defered WHERE clause expressions in LINQ to SQL

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!

Upvotes: 2

Views: 811

Answers (1)

KristoferA
KristoferA

Reputation: 12397

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...

Upvotes: 6

Related Questions