C# loop over an array of unknown dimensions

后端 未结 3 570
粉色の甜心
粉色の甜心 2021-01-15 04:23

I want to create an extension method to loop over System.Array with unknown number of dimensions

For now I am using a naive approach:

pu         


        
3条回答
  •  醉酒成梦
    2021-01-15 05:23

    If you don't care about the indices, you can just iterate over a System.Array with absolutely no knowledge of its Rank. The enumerator will hit every element.

    public class Program
    {
        public static void IterateOverArray(System.Array a)
        {
            foreach (var i in a)
            {
                Console.WriteLine(i);
            }
        }
    
        public static void Main()
        {
            var tests = new System.Array []
            {
                new int[] {1,2,3,4,5,6,7,8},
                new int[,]
                {
                    {1,2},{3,4},{5,6},{7,8}
                },
                new int[,,]
                {
                    {  {1,2},{3,4} },
                    {  {5,6},{7,8} }
                }
            };
    
    
            foreach (var t in tests)
            {
                Console.WriteLine("Dumping array with rank {0} to console.", t.Rank);
                IterateOverArray(t);
            }
        }
    }
    

    Output:

    Dumping array with rank 1 to console.
    1
    2
    3
    4
    5
    6
    7
    8
    Dumping array with rank 2 to console.
    1
    2
    3
    4
    5
    6
    7
    8
    Dumping array with rank 3 to console.
    1
    2
    3
    4
    5
    6
    7
    8
    

    Link to DotNetFiddle example

提交回复
热议问题