Linq in for loop

Will this linq statement be executed every time in every loop? Does the for loop somehow save the linq result?

for(int i = 0; i < mylist.Where(x => x > 10).ToList().Count; i++) 

Sorry if you duplicate

+5
source share
3 answers

I ran the following code in LINQPad:

 for(int i = 0; i < 10.Dump(); i++) { } 

The result is:

enter image description here

So, I think the answer is yes, it will execute it several times.

+4
source

Yes, it will work, but I would suggest better try to save it in an int variable.

 int k = mylist.Where(x => x > 10).ToList().Count; for(int i = 0; i < k; i++) 

It makes it more readable.

+3
source

You can also use this:

 mylist.Where(x => x > 10) .Select((x,index) => ExecuteYourFunction(x, index)); 

Or if your method has no return value:

 mylist.Where(x => x > 10) .Select((x,index) => new { Index = index, Value= x }) .ToList() .Foreach(myType => ExecuteYourFunction(myType.Name, myType.Index)); 
+3
source

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


All Articles