Loop loop problem for Iqueyable

Can I use a foreach loop for an Iqueryable object?

I would like to do something like the following:

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

This gives me the wrong conclusion as every time value if I change.

+3
source share
3 answers

The problem you are facing is delayed execution, you should be able to find a lot of information about it, but basically none of them are executed until you actually try to read the data from IQueryable (convert it to IEnumerable or List or other similar operations). This means that all this happens after the completion of foreach, when I am set to the final value.

, , for :

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

, , IQueryable.

+3

, :

query = objDataContext.Myclass.Where(q => (arr1.Contains(q.f_id1) || arr1.Contains(q.f_id2) || arr1.Contains(q.f_id3));
+1

this is because " i" is not evaluated until you really use the iteration of the query collection at the time. I believe that " i" will be the last.

0
source

Source: https://habr.com/ru/post/1748276/


All Articles