A question about understanding linq and Lambda

T

Tony Johansson

Hello!

In this simple example where I have two operators which are .Where and
..OrderBy.
I just wonder how this work. As I have understood it works like this.
First will the Where clause be called to return true for all value in the
collection that is less then 4 which give 2 ,1 and 3
But now which data will be input to the last operator OrderBy ?
So will the operator .OrderBy have as input those values that is return as
true from the Where operator whic is 2 ,1 and 3


int[] nums = new int[]{6,2,7,1,9,3};
IEnumerable<int> numsLessThenFour = nums
..Where(i => i<4)
..OrderBy(i => i);

//Tony
 
P

Peter Morris

int[] nums = new int[]{6,2,7,1,9,3};
var numsLessThanFour = nums
.Where(i => i<4);

This alone would not read from "nums". Only when you start to iterate
through numsLessThanFour would nums start to be iterated.


int[] nums = new int[]{6,2,7,1,9,3};
var numsLessThanFour = nums
.Where(i => i<4);
.OrderBy(i => i);

To order the collection the whole collection needs to be known. None of
this is evaluated until you start to iterate over numsLessThanFour, but as
soon as you ask for the first value the OrderBy will retrieve all matches
from the Where and then order them. This will happen only once, as you
continue to iterate over numsLessThanFour you will be returned the cached
sorted results.

I believe that is how it works anyway. Did that answer your question?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top