tags:

views:

39

answers:

3

Hi,

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));
}

It gives me wrong output as each time value if i is changed.

+1  A: 

You dont need a for each, try it like this:

query = objDataContext.Myclass.Where(q => (arr1.Contains(q.f_id1) || arr1.Contains(q.f_id2) || arr1.Contains(q.f_id3));
alejandrobog
@alejandrobog logically it'll give incorrect filter, try to run that query in SQL!
Vikas
see this two queries are different:select * from MyClass where (f_id1 = 1 or f_id2 = 1 or f_id3 = 1) and (f_id1 = 3 or f_id2 = 3 or f_id3 = 3);select * from MyClass where (f_id1 in (1,3) or f_id2 in (1,3) or f_id3 in (1,3))
Vikas
You are right, sorry I misunderstood the logic
alejandrobog
A: 

this is because "i" is not evaluated until you really use the iterate the query collectionif not by that time I believe "i" will be the last.

Oscar Cabrero
+3  A: 

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.

Tim Schneider