Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clarify what select does

Tags:

arrays

c#

I haven't been able to find anything on google.

I have this piece of code:

Random r = new Random();
int[] output = Enumerable.Range(0, 11).Select(x => x / 2).OrderBy(x => r.Next()).ToArray();

and I am having trouble actually understanding what each element does.

It generates a range of numbers and elements between 0 and 11. But what does the select(x => x / 2) do ? does it just make pairs of elements,

I know what the whole thing spits out, an array with pairs of numbers, with a single number which has no pair.

but it is a bit above me to fully understand it ?

( is this even okay to ask on here ?? or should I delete the question again ? )

like image 882
andrelange91 Avatar asked Aug 24 '17 09:08

andrelange91


1 Answers

It generates a range of numbers and elements between 0 and 11. But what does the select(x => x / 2) do ? does it just make pairs of elements.

No, Select does what in some programming languages is known as map. It is called on an IEnumerable<T> and has as parameter Func<T,U> a function, and it produces an IEnumerable<U> where each element if the given IEnumerable<T> is processes through the function and the result is emitted in the result.

So in this case, it will take a range from 0 to (excluding) 11, and for each of those integers, perform an integer divsion by two:

csharp> Enumerable.Range(0, 11);
{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
csharp> Enumerable.Range(0, 11).Select(x => x/2);
{ 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5 }

Since:

   { 0/2, 1/2, 2/2, 3/2, 4/2, 5/2, 6/2, 7/2, 8/2, 9/2, 10/2 }
== { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5 }

Later then that IEnumerable<int> is reordered (using the OrderBy) by using pseudo-random numbers (so we shuffle them) and converted into a list.

like image 151
Willem Van Onsem Avatar answered Oct 19 '22 06:10

Willem Van Onsem