Search code examples
c#linq-to-sql

Foreach loop problem for IQueryable object


Can we use foreach loop for IQueryable object?

I'd like to do something as follow:

query = IQueryable<Myclass> = objDataContext.Myclass; // objDataContext is an object of LINQ datacontext class

int[] arr1 = new int[] { 3, 4, 5 };

foreach (int i in arr1)
{
     query = query.Where(q => (q.f_id1 == i || q.f_id2 == i || q.f_id3 == i));
}

I get a wrong output as each time value of i is changed.


Solution

  • The problem you're facing is deferred execution, you should be able to find a lot of information on this but basically none of the code s being executed until you actually try to read data from the IQueryable (Convert it to an IEnumerable or a List or other similar operations). This means that this all happens after the foreach is finished when i is set to the final value.

    If I recall correctly one thing you can do is initialize a new variable inside the for loop like this:

    foreach (int i in arr1)
    {
       int tmp = i;
       query = query.Where(q => (q.f_id1 == tmp || q.f_id2 == tmp || q.f_id3 == tmp));
    }
    

    By putting it in a new variable which is re-created each loop, the variable should not be changed before you execute the IQueryable.