Csharp/C Sharp/Collections Data Structure/Array Dimension

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Call GetLength for two dimenional array

<source lang="csharp"> using System; class ChessBoard {

   static void Main(String[] args) {
       Char[,] SquareColor = new Char[8, 8];
       for (int i = 0; i < SquareColor.GetLength(0); i++) {
           for (int x = 0; x < SquareColor.GetLength(1); x++) {
               if ((x % 2) == 0)
                   if ((i % 2) == 0)
                       SquareColor[i, x] = "W";
                   else
                       SquareColor[i, x] = "B";
               else
                   if ((i % 2) == 0)
                       SquareColor[i, x] = "B";
                   else
                       SquareColor[i, x] = "W";
           }
       }
       for (int i = 0; i < SquareColor.GetLength(0); i++) {
           for (int x = 0; x < SquareColor.GetLength(1); x++) {
               Console.Write(SquareColor[i, x]);
           }
           Console.WriteLine();
       }
   }

}

</source>


Catch IndexOutOfRangeException Exception

<source lang="csharp">

using System;

class MainClass {

   public static void Main()
   {
       try
       {
           int [] IntegerArray = new int [5];
  
           IntegerArray[10] = 123;
       }
       catch(IndexOutOfRangeException)
       {
           Console.WriteLine("An invalid element index access was attempted.");
       }
   }

}

      </source>


Catch OutOfMemoryException

<source lang="csharp">

using System;

class MainClass {

   public static void Main()
   {
       int [] LargeArray;
  
       try
       {
           LargeArray = new int [2000000000];
       }
       catch(OutOfMemoryException)
       {
           Console.WriteLine("The CLR is out of memory.");
       }
   }

}

      </source>


Demonstrate a two-dimensional array

<source lang="csharp"> // Demonstrate a two-dimensional array. using System; public class TwoD {

 public static void Main() {  
   int t, i; 
   int[,] table = new int[3, 4];  
 
   for( t = 0; t < 3; ++t) {  
     for(i = 0; i < 4; ++i) {  
       table[t,i] = (t*4)+i+1;  
       Console.Write(table[t,i] + " ");  
     }  
     Console.WriteLine(); 
   }  
 } 

}

      </source>


Demonstrate jagged arrays

<source lang="csharp"> // Demonstrate jagged arrays. using System;

public class Jagged1 {

 public static void Main() {  
   int[][] jagged = new int[3][];  
   jagged[0] = new int[4];  
   jagged[1] = new int[3];  
   jagged[2] = new int[5];  
 
   int i; 

   // store values in first array 
   for(i=0; i < 4; i++)   
     jagged[0][i] = i;  

   // store values in second array 
   for(i=0; i < 3; i++)   
     jagged[1][i] = i;  

   // store values in third array 
   for(i=0; i < 5; i++)   
     jagged[2][i] = i;  


   // display values in first array 
   for(i=0; i < 4; i++)   
     Console.Write(jagged[0][i] + " ");  

   Console.WriteLine(); 

   // display values in second array 
   for(i=0; i < 3; i++)   
     Console.Write(jagged[1][i] + " ");  

   Console.WriteLine(); 

   // display values in third array 
   for(i=0; i < 5; i++)   
     Console.Write(jagged[2][i] + " ");  

   Console.WriteLine(); 
 }  

}

      </source>


Demonstrate Length with jagged arrays

<source lang="csharp"> // Demonstrate Length with jagged arrays.

using System;

public class Jagged {

 public static void Main() {  
   int[][] network_nodes = new int[4][];  
   network_nodes[0] = new int[3];  
   network_nodes[1] = new int[7];  
   network_nodes[2] = new int[2];  
   network_nodes[3] = new int[5];  

 
   int i, j; 

   // fabricate some fake CPU usage data    
   for(i=0; i < network_nodes.Length; i++)   
     for(j=0; j < network_nodes[i].Length; j++)  
       network_nodes[i][j] = i * j + 70;  


   Console.WriteLine("Total number of network nodes: " + network_nodes.Length + "\n"); 

   for(i=0; i < network_nodes.Length; i++) {  
     for(j=0; j < network_nodes[i].Length; j++) { 
       Console.Write("CPU usage at node " + i +  
                     " CPU " + j + ": "); 
       Console.Write(network_nodes[i][j] + "% ");  
       Console.WriteLine();  
     } 
     Console.WriteLine();  
   } 

 }  

}

      </source>


illustrates the use of a two-dimensional rectangular array

<source lang="csharp"> /*

 illustrates the use of a two-dimensional rectangular array
  • /

using System; public class Example10_6 {

 public static void Main()  {
   const int rows = 8;
   const int columns = 8;
   string[,] chessboard = new string[rows, columns];
   chessboard[0, 0] = "White Rook";
   chessboard[1, 0] = "White Pawn";
   chessboard[2, 3] = "White King";
   chessboard[3, 5] = "Black Bishop";
   chessboard[4, 4] = "Black Pawn";
   chessboard[5, 3] = "Black King";
   for (int row = 0; row < rows; row++)
   {
     for (int column = 0; column < columns; column++)
     {
       Console.WriteLine("chessboard[" + row + ", " + column + "] = " +
         chessboard[row, column]);
     }
   }
 }

}


      </source>


Initialize a two-dimensional array

<source lang="csharp"> // Initialize a two-dimensional array.

using System;

public class Squares {

 public static void Main() {  
   int[,] sqrs = { 
     { 1, 1 }, 
     { 2, 4 }, 
     { 3, 9 }, 
     { 4, 16 }, 
     { 5, 25 }, 
     { 6, 36 }, 
     { 7, 49 }, 
     { 8, 64 }, 
     { 9, 81 }, 
     { 10, 100 } 
   }; 
   int i, j; 

   for( i = 0; i < 10; i++) {  
     for(j = 0; j < 2; j++)  
       Console.Write(sqrs[i,j] + " ");   
     Console.WriteLine();  
   }  
 }  

}

      </source>


initialize a two-dimensional rectangular array, and use the array properties and methods

<source lang="csharp"> /* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110

  • /

/*

 Example10_7.cs illustrates how to initialize
 a two-dimensional rectangular array, and use the
 array properties and methods
  • /

using System; public class Example10_7 {

 public static void Main()
 {
   // create and initialize the names array
   string[,] names =
   {
     {"Jason", "Marcus", "Price"},
     {"Steve", "Edward", "Smith"},
     {"Cynthia", "Ann", "Williams"},
     {"Gail", "Patricia", "Jones"},
   };
   // display the Rank and Length properties of the names array
   Console.WriteLine("names.Rank (number of dimensions) = " + names.Rank);
   Console.WriteLine("names.Length (number of elements) = " + names.Length);
   // use the GetLength() method to get number of elements
   // in each dimension of the names array
   int numberOfRows = names.GetLength(0);
   int numberOfColumns = names.GetLength(1);
   Console.WriteLine("Number of rows = " + numberOfRows);
   Console.WriteLine("Number of columns = " + numberOfColumns);
   // display the elements of the names array
   for (int row = 0; row < numberOfRows; row++)
   {
     for (int column = 0; column < numberOfColumns; column++)
     {
       Console.WriteLine("names[" + row + ", " + column + "] = " +
         names[row, column]);
     }
   }
 }

}

      </source>


Multidimensional and Jagged Arrays:Jagged Arrays

<source lang="csharp"> // using System; public class JaggedArrays {

   public static void Main()
   {
       int[][] matrix = {new int[5], new int[4], new int[2] };
       matrix[0][3] = 4;
       matrix[1][1] = 8;
       matrix[2][0] = 5;
       
       for (int i = 0; i < matrix.Length; i++)
       {
           for (int j = 0; j < matrix[i].Length; j++)
           {
               Console.WriteLine("matrix[{0}, {1}] = {2}", i, j, matrix[i][j]);
           }
       }       
   }

}

      </source>


Multi dimensional Arrays 1

<source lang="csharp"> using System; public class MultidimensionalArrays {

   public static void Main()
   {
       int[,] matrix = { {1, 1}, {2, 2}, {3, 5}, {4, 5}, {134, 44} };
       
       for (int i = 0; i < matrix.GetLength(0); i++)
       {
           for (int j = 0; j < matrix.GetLength(1); j++)
           {
               Console.WriteLine("matrix[{0}, {1}] = {2}", i, j, matrix[i, j]);
           }
       }       
   }

}

      </source>


Sum the values on a diagonal of a atrix

<source lang="csharp"> // Sum the values on a diagonal of a 3x3x3 matrix. using System;

public class ThreeDMatrix {

 public static void Main() {  
   int[,,] m = new int[3, 3, 3]; 
   int sum = 0; 
   int n = 1; 

   for(int x=0; x < 3; x++) {
     for(int y=0; y < 3; y++) {
       for(int z=0; z < 3; z++) { 
         m[x, y, z] = n++; 
       }  
     }  
   }  


   sum = m[0,0,0] + m[1,1,1] + m[2, 2, 2]; 

   Console.WriteLine("Sum of first diagonal: " + sum); 
 }  

}

      </source>


the use of a jagged array

<source lang="csharp"> /* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110

  • /

/*

 Example10_9.cs illustrates the use of a jagged array
  • /

using System; public class Example10_9 {

 public static void Main()
 {
   // declare a jagged array of four rows,
   // with each row consisting of a string array
   string[][] names = new string[4][];
   // the first row is an array of three strings
   names[0] = new string[3];
   names[0][0] = "Jason";
   names[0][1] = "Marcus";
   names[0][2] = "Price";
   // the second row is an array of two strings
   names[1] = new string[2];
   names[1][0] = "Steve";
   names[1][1] = "Smith";
   // the third row is an array of four strings
   names[2] = new string[] {"Cynthia", "Ann", "Jane", "Williams"};
   names[3] = new string[] {"Gail", "Jones"};
   // display the Rank and Length properties for the names array
   Console.WriteLine("names.Rank = " + names.Rank);
   Console.WriteLine("names.Length = " + names.Length);
   // display the Rank and Length properties for the arrays
   // in each row of the names array
   for (int row = 0; row < names.Length; row++)
   {
     Console.WriteLine("names[" + row + "].Rank = " + names[row].Rank);
     Console.WriteLine("names[" + row + "].Length = " + names[row].Length);
   }
   // display the array elements for each row in the names array
   for (int row = 0; row < names.Length; row++)
   {
     for (int element = 0; element < names[row].Length; element++)
     {
       Console.WriteLine("names[" + row + "][" + element + "] = " +
         names[row][element]);
     }
   }
 }

}


      </source>


the use of a three-dimensional rectangular array

<source lang="csharp"> /* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110

  • /

/*

 Example10_8.cs illustrates the use of
 a three-dimensional rectangular array
  • /

using System; public class Example10_8 {

 public static void Main()
 {
   // create the galaxy array
   int[,,] galaxy = new int [10, 5, 3];
   // set two galaxy array elements to the star"s brightness
   galaxy[1, 3, 2] = 3;
   galaxy[4, 1, 2] = 9;
   // display the Rank and Length properties of the galaxy array
   Console.WriteLine("galaxy.Rank (number of dimensions) = " + galaxy.Rank);
   Console.WriteLine("galaxy.Length (number of elements) = " + galaxy.Length);
   // display the galaxy array elements, but only display elements that
   // have actually been set to a value (or "contain stars")
   for (int x = 0; x < galaxy.GetLength(0); x++)
   {
     for (int y = 0; y < galaxy.GetLength(1); y++)
     {
       for (int z = 0; z < galaxy.GetLength(2); z++)
       {
         if (galaxy[x, y, z] != 0)
         {
           Console.WriteLine("galaxy[" + x + ", " + y + ", " + z +"] = " +
             galaxy[x, y, z]);
         }
       }
     }
   }
 }

}

      </source>


Uses a jagged array to store sales figures

<source lang="csharp"> /* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794

  • /

// Sales.cs -- Uses a jagged array to store sales figures, then writes report // for one month. Demonstrates that you do not have to worry about // looking for empty elements. // // Compile this program with the following command line: // C:>csc Sales.cs // namespace nsSales {

   using System;
   
   public class Sales
   {
       static public void Main ()
       {
            DateTime now = DateTime.Now;
            Random rand = new Random ((int) now.Millisecond);
            int [] MonthLen = new int []
                          {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
            double [][] Sales2000 = new double [12][];
            for (int x = 0; x < MonthLen.Length; ++x)
            {
                Sales2000[x] = new double [MonthLen[x]];
                for (int y = 0; y < Sales2000[x].Length; ++y)
                {
                    Sales2000[x][y] = rand.NextDouble() * 100;// % 11 + 20;
                }
            }
            Console.Write ("February Sales Report (in thousands):");
            for (int x = 0; x < Sales2000[1].Length; ++x)
            {
                 if ((x % 4) == 0)
                     Console.WriteLine ();
                 Console.Write ("    Feb. {0,-2:D}: {1,-4:F1}", x + 1, Sales2000[1][x]);
            }
       }
   }

}


      </source>


Uses a two-dimensional array to store grades for students

<source lang="csharp"> /* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794

  • /

// Grades.cs -- Uses a two-dimensional array to store grades for students // // Compile this program with the following command line: // C:>csc Grades.cs namespace nsGrades {

   using System;
   
   public class Grades
   {
       static public void Main ()
       {
            DateTime now = DateTime.Now;
            Random rand = new Random ((int) now.Millisecond);
            int [,] Grades = new int [5,10];
            for (int x = 0; x < Grades.GetLength (0); ++x)
            {
                for (int y = 0; y < Grades.GetLength(1); ++y)
                {
                    Grades [x, y] = 70 + rand.Next () % 31;
                }
            }
            int [] Average = new int [10];
            Console.WriteLine ("Grade summary:\r\n");
            Console.WriteLine ("Student   1   2   3   4   5   6   7   8   9  10");
            Console.WriteLine ("        ----------------------------------------");
            for (int x = 0; x < Grades.GetLength (0); ++x)
            {
                Console.Write ("Test " + (x + 1) + " ");
                for (int y = 0; y < Grades.GetLength(1); ++y)
                {
                    Average[y] += Grades[x,y];
                    Console.Write ("{0,4:D}", Grades[x,y]);
                }
                Console.WriteLine ();
            }
            Console.Write ("\r\n Avg.  ");
            foreach (int Avg in Average)
            {
                Console.Write ("{0,4:D}", Avg / Grades.GetLength(0));
            }
            Console.WriteLine ();
       }
   }

}


      </source>


Use the Length array property on a 3-D array

<source lang="csharp"> // Use the Length array property on a 3-D array.

using System;

public class LengthDemo3D {

 public static void Main() {  
   int[,,] nums = new int[10, 5, 6];  

   Console.WriteLine("Length of nums is " + nums.Length);  
 
 }  

}

      </source>