Iterate Array and do action - CSharp System

CSharp examples for System:Array Element

Description

Iterate Array and do action

Demo Code

// Copyright (c) Microsoft Corporation. All rights reserved.
using System.Linq;
using System;//from ww  w  . ja v  a  2s.c o  m

public class Main{
        private static void Iterate(Array array, int[] indices, int dimension, Action<int[]> action)
        {
            if (dimension >= indices.Length)
            {
                action(indices);
            }
            else
            {
                var lowerBound = array.GetLowerBound(dimension);
                var upperBound = array.GetUpperBound(dimension);
                for (var index = lowerBound; index <= upperBound; index++)
                {
                    indices[dimension] = index;
                    Iterate(array, indices, dimension + 1, action);
                }
            }
        }
        public static void Iterate(this Array array, Action<int[]> action)
        {
            if (array.Rank > 0)
            {
                var dimensions = Enumerable.Range(0, array.Rank);
                if (dimensions.Aggregate(1, (count, dimension) => count * array.GetLength(dimension)) > 0)
                {
                    Iterate(array, new int[array.Rank], 0, action);
                }
            }
        }
}

Related Tutorials