澄清选择的作用

and*_*e91 6 c# arrays

我一直无法在谷歌上找到任何东西.

我有这段代码:

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

而我实际上无法理解每个元素的作用.

它生成一系列0到11之间的数字和元素.但是select(x => x/2)是做什么的?它只是制作成对的元素,

我知道整个东西吐出来的东西,一个带有数字对的数组,一个没有对的数字.

但完全理解它有点高于我吗?

(这可以在这里问吗?或者我应该再次删除这个问题?)

Wil*_*sem 8

它生成一系列0到11之间的数字和元素.但是select(x => x/2)是做什么的?它只是制作成对的元素.

不,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 }
Run Code Online (Sandbox Code Playgroud)

以来:

   { 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 }
Run Code Online (Sandbox Code Playgroud)

之后,通过使用随机数(因此我们将它们混洗)IEnumerable<int>重新排序(使用)并转换为列表.OrderBy


Owe*_*ing 7

    .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
Run Code Online (Sandbox Code Playgroud)


Swe*_*per 7

想象一下,Select对每个元素进行转换IEnumerable.

例如,假设我们有一个这样的列表:

0 1 2 3 4 5 6 7 8 9 10
Run Code Online (Sandbox Code Playgroud)

然后我们调用.Select(x => x / 2),我们说对于x列表中的每个元素,执行以下转换:

x / 2
Run Code Online (Sandbox Code Playgroud)

我们将列表中的每个元素除以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
Run Code Online (Sandbox Code Playgroud)

我们得到了

0 0 1 1 2 2 3 3 4 4 5 5
Run Code Online (Sandbox Code Playgroud)