[英]C# double for comprehension?
Is it possible to do a double for
comprehension in C#? 是否有可能做一个双重for
在C#中的理解? For example, the following works: 例如,以下工作:
var a = new[] { 1, 2, 3 };
var b = Enumerable.Range(0, a.Length).Select(i => a[i]).ToArray();
But when I try and adapt this code for the two-dimensional case, things don't work. 但是,当我尝试将此代码用于二维情况时,事情就不起作用了。 Below I'm trying to iterate over the pixels of a bitmap: 下面,我尝试遍历位图的像素:
Color[] p = Enumerable.Range(0, Source.Width).Select(i => Enumerable.Range(0, Source.Height).Select(j => Source.GetPixel(i, j))).ToArray()
. Color[] p = Enumerable.Range(0, Source.Width).Select(i => Enumerable.Range(0, Source.Height).Select(j => Source.GetPixel(i, j))).ToArray()
。
Is there any way to get what I want? 有什么办法得到我想要的吗? The error I'm currently getting is: 我目前收到的错误是:
Cannot implicitly convert type System.Collections.Generic.IEnumerable[] to System.Drawing.Color[] 无法将类型System.Collections.Generic.IEnumerable []隐式转换为System.Drawing.Color []
The outer Select
needs to be a SelectMany
to flatten the projection: 外部Select
必须为SelectMany
才能使投影变平:
Color[] p = Enumerable.Range(0, Source.Width)
.SelectMany(i => Enumerable.Range(0, Source.Height)
.Select(j => Source.GetPixel(i, j)))
.ToArray();
or to create a jagged 2-D array add an inner ToArray()
: 或创建一个锯齿状的二维数组,请添加一个内部ToArray()
:
Color[][] p = Enumerable.Range(0, Source.Width)
.Select(i => Enumerable.Range(0, Source.Height)
.Select(j => Source.GetPixel(i, j))
.ToArray())
.ToArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.