Clarify what chooses

I could not 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 understanding what each element does.

It generates a range of numbers and elements between 0 and 11. But what makes the choice (x => x / 2)? it just creates pairs of elements,

I know that it all splashes out, an array with pairs of numbers, with one number that does not have a pair.

but a little taller than me to fully understand this?

(is it even ok to ask here? or do I need to delete the question again?)

+6
source share
4 answers

It generates a range of numbers and elements between 0 and 11. But what makes the choice (x => x / 2)? it just creates pairs of elements .

, Select , map. IEnumerable<T> Func<T,U> , IEnumerable<U>, , IEnumerable<T> , .

, 0 () 11, divsion :

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 }

   { 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 }

, IEnumerable<int> ( OrderBy), ( ) .

+8
    .Range(0, 11) // generate a sequence of integers starting at 0 and incrementing 11 times (i.e. the values 0 up to and including 10)
    .Select(x => x / 2) // divide each of those values from previous result by 2 and return them
    .OrderBy(x => r.Next()) // then order them randomly using a random number
    .ToArray(); // return the end result as an array
+6

Select IEnumerable.

, , , :

0 1 2 3 4 5 6 7 8 9 10

.Select(x => x / 2), , x :

x / 2

:

Original    Transformation    Result
0           0 / 2             0
1           1 / 2             0
2           2 / 2             1
3           3 / 2             1
4           4 / 2             2
5           5 / 2             2
6           6 / 2             3
7           7 / 2             3
8           8 / 2             4
9           9 / 2             4
10          10 / 2            5

0 0 1 1 2 2 3 3 4 4 5 5
+6
source

What he Select()does is that he evaluates the given expression for each element Enumerablethat he called (the original list), and returns a new one Enumerablewith the results.

For the list:

[2, 4, 6]

he will return:

[2/2, 4/2, 6/2]

where /"division" means, so the result Select()(and not the entire LINQ chain) will be:

[1, 2, 3]

Similarly, if your source list is:

words = ["dog", "child", "building"]

And you call:

words.Select(word => word.Length)

you get a list of all the lengths of the lines in the list in order:

[3, 5, 7]
+4
source

All Articles