Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq in For Loop [duplicate]

Tags:

c#

Is this linq statement gonna be executed everytime in each loop? Does somehow the for loop store the linq result?

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

Sorry in case of a duplicate

like image 505
dev hedgehog Avatar asked Sep 05 '14 08:09

dev hedgehog


Video Answer


2 Answers

I ran the following code in LINQPad:

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

The result was:

enter image description here

So, i think the answer is yes, it will execute it multiple times.

like image 129
Giannis Paraskevopoulos Avatar answered Nov 11 '22 21:11

Giannis Paraskevopoulos


Yes it would work but I would suggest to better try to store it in a int variable

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

This makes it more readable

like image 44
Rahul Tripathi Avatar answered Nov 11 '22 21:11

Rahul Tripathi