将1D数组索引转换为2D数组索引
我有2个arrays。 我想将第一个数组的索引转换为第二个数组。 有没有比我下面更好的方法呢?
Array array1[9]; Array array2[3][3]; // Index is the index of the 1D array public Point convert1Dto2D(int index) { Point p = new Point(); switch (index) { case 0: px = 0; py = 0; break; case 1: px = 0; py = 1; break; case 2: px = 0; py = 2; break; case 3: px = 1; py = 0; break; case 4: px = 1; py = 1; break; case 5: px = 1; py = 2; break; case 6: px = 2; py = 0; break; case 7: px = 2; py = 1; break; case 8: px = 2; py = 2; break; } return p; }
px = index / 3; py = index % 3;
您可以使用模数和整数除法进行数学运算,假设您的第二个数组是3×3数组,以下将执行此操作。
py = index % 3; px = index / 3;
我假设您在循环中运行该代码? 如果是这样
IEnumerable DoStuff(int length, int step) { for (int i = 0; i < length; i++) yield return new Point(i/step, i%step); }
叫它
foreach (var element in DoStuff(9, 3)) { Console.WriteLine(element.X); Console.WriteLine(element.Y); }
- C#IEnumerable打印出来
- 如何在不关闭它的情况下在同一浏览器实例中运行多个测试方法(C#,SeleniumWebDriverz NUnit)?
- 如何在Windows Universal App中使用双工wcf服务
- 从C#项目中的自定义文件夹中获取文件
- TcpListener:如何在等待AcceptTcpClientAsync()时停止侦听?
- 如何在Entity Framework 4.1的Code-First Fluent API中以编程方式定义关系
- 如何在c#windows应用程序中引用网站usercontrol?
- 如何使用ANTLR获取Lexer和Parser for C#?
- 将List 绑定到Crystal Report的对象