Foreach and string index : Array ForEach « Data Structure « C# / CSharp Tutorial






using System;

  class Class1
  {
    [STAThread]
    static void Main(string[] args)
    {
            string[,,] arr1 = new string[3,2,3];

            for( int row = 0; row < 3; row++ )
            {
                for( int col = 0; col < 2; col++ )
                {
                    for( int z = 0; z < 3; z++ )
                        arr1[row,col,z] = row + "," + col + "," + z;
                }
            }

            int idx = 0;
            foreach( string elem in arr1 )
            {
                Console.Write("indices = [ ");
                foreach( int i in GetDimensionIndices(idx, arr1) )
                {
                    Console.Write( "{0} ", i );
                }
                Console.WriteLine( "] string = {0}", elem );
                idx++;
            }
        }

        static int[] GetDimensionIndices( int flatIndex, Array array )
        {
            int[] indices = new int[ array.Rank ];

            int p = 1;
            for( int i = array.Rank-1; i >= 0; i-- )         
            {
                indices[i] = (((flatIndex/p)) % (array.GetUpperBound(i)+1));

                if( i > 0)
                {
                    p *= array.GetUpperBound( i )+1;
                }
            }
            return indices;
        }
  }








11.15.Array ForEach
11.15.1.Array.ForEach with a delegate
11.15.2.An Action triggered by Array.ForEach
11.15.3.Use an Action to change the values
11.15.4.foreach with Arrays
11.15.5.Foreach and string index