对于二维System.Array,foreach迭代是如何发生的?

时间:2009-08-21 09:57:33

标签: c#

假设我们正在创建一个System.Array


      Array _twoD = Array.CreateInstance(typeof(string), 2,2);


        _twoD.SetValue("Harrish", 0, 0);
        _twoD.SetValue("Goel", 0, 1);
        _twoD.SetValue("Prakash", 1, 0);
        _twoD.SetValue("Manish", 1, 1);
        foreach (string str in _twoD)
        {
            Console.WriteLine(str);
        }

Enumerator如何自动迭代[0,0] [0,1],[1,0],[1,1]?

[对于单维数组,很容易理解,2D和3D内部会发生什么? ]

我们可以使用System.Array创建Jagged Style数组吗?

4 个答案:

答案 0 :(得分:6)

来自msdn

  

System.Array类型(第12.1.1节)   是一个集合类型,因为所有   数组类型派生自System.Array,   允许任何数组类型表达式   在foreach声明中。订单中   哪个foreach遍历元素   数组如下:For   一维数组,元素   正在增加指数   顺序,从索引0开始   以索引长度结束 - 1. For   多维数组,元素是   遍历了这样的指数   最右边的尺寸增加了   首先,然后是下一个左维,   等等在左边。

答案 1 :(得分:4)

是的,它将会[0,0],[0,1]等。您可以通过使用new string[2,2]直接在C#中创建2D数组来更轻松地看到这一点。

作为演示:

using System;

public class Test
{
    static void Main(string[] args)
    {
        string[,] strings = new string[2,2];
        // Just to make things absolutely explict
        strings[0,0] = "0,0";
        strings[0,1] = "0,1";
        strings[1,0] = "1,0";
        strings[1,1] = "1,1";

        foreach (string x in strings)
        {
            Console.WriteLine(x);
        }
    }
}

输出:

0,0
0,1
1,0
1,1

使用System.Array创建锯齿状数组只是创建一个元素类型为string[]等的数组。锯齿状数组只是一个数组数组。

答案 2 :(得分:2)

对于枚举锯齿状数组,SelectMany(LINQ)是你的朋友:

    int[][] data = { new int[] {0,1,2},
                       new int[] {3,4},
                       new int[] {5,6,7,8}};
    foreach (int i in data.SelectMany(row => row))
    {
        Console.WriteLine(i);
    }

或者在查询语法中:

    int[][] data = { new int[] {0,1,2},
                       new int[] {3,4},
                       new int[] {5,6,7,8}};
    foreach (int i in from row in data
                      from cell in row
                      select cell)
    {
        Console.WriteLine(i);
    }

答案 3 :(得分:1)

数组是逐行枚举的,然后逐列枚举

        var array = new[,]{
            {"A1","A2","A3"},
            {"B1","B2","B3"}
        };

        foreach (var item in array)
        {
            Console.WriteLine(item);
        }

显示:

  

A1

     

A2

     

A3

     

B1

     

B2

     

B3

关于你的第二个问题:

  

我们可以使用System.Array创建Jagged Style数组吗?

不直接。锯齿状数组是一个数组数组,所以你必须编写类似的东西:

        Array array = Array.CreateInstance(typeof(int[]), 2);
        for (int i = 0; i < array.Length; i++)
        {
            array.SetValue(Array.Create(typeof(int) 3), i);
        }
相关问题