简体   繁体   中英

C# double for comprehension?

Is it possible to do a double for comprehension in 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() .

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[]

The outer Select needs to be a SelectMany to flatten the projection:

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() :

Color[][] p = Enumerable.Range(0, Source.Width)
                        .Select(i => Enumerable.Range(0, Source.Height)
                                               .Select(j => Source.GetPixel(i, j))
                                               .ToArray())
                        .ToArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM