Tuesday, September 28, 2010

Arrrays in Csharp

Arrays in csharp:
            Arrays provide the same functionality and they work similarly to how the arrays work in other programming languages. However, there are few things which you might keep in mind while working with arrays. This article explains about the different types of arrays, their methods and how to work with them.
Arrays in c# are not dynamic in size, they are fixed in size. Arrays are zero indexed, that is array index starts at zero and the total number of elements in an array is n-1. An array is represented by a single variable name. The individual elements are accessed using the variable name together with one or more indexes between. For example consider an instance where you need to display the list of products available at an Electronic Gadgets Store. One can use any one of the following syntax to accomplish this task.
Array Syntax:
string[ ] products;
products = new string[3];
products[0] = "Griffin iTrip FM Transmitter”;
products[1] = "Griffin DJ Cable";
products[1] = "USB Power Adapter";
Or
You can specific the length of the array at the time of variable declaration.
string[ ] products = new string[3];
products[0] = "Griffin iTrip FM Transmitter”;
products[1] = "Griffin DJ Cable";
products[1] = "USB Power Adapter";
Or
Entire Declaration at same time
string[ ] products = new string[ 3]  { " Griffin iTrip FM Transmitter”, " Griffin DJ Cable ", " USB Power Adapter " };
 Or
 You can also omit the size and new operator as shown:
 string[ ] products = new string[ ] { " Griffin iTrip FM Transmitter”, " Griffin DJ Cable ", " USB Power Adapter " };
string[ ] products = { " Griffin iTrip FM Transmitter”, " Griffin DJ Cable ", " USB Power Adapter " };

 Multi Dimension Arrays:
Multi Dimension Arrays are of two types Rectangular Arrays and Jagged Arrays.
Rectangular Arrays are arrays in which all the sub arrays in a particular dimension have same length. In our example we can use Multi Dimension Arrays to add some information for the products like Product ID and product code.
string[,] productattributes = new string[3,3] { { "GIFT", "Griffin iTrip FM Transmitter", "$42" }, 
{ "GDC", "Griffin DJ Cable", "$67" }, { "UPA", "USB Power Adapter", "$76" } };
 All the syntax declarations which are used for the single dimension array can be used for the multi dimension arrays.
 Similarly we can increase the dimension of the array to make it as three dimension. By using these three dimension array we categorize the products. The syntax for the three dimension array goes here.
Syntax:
string [, ,] productcateogries = new string[3, 1, 4]
{{{“Car Accessories", "GIFT", "Griffin iTrip FM Transmitter", "$42" } },
  {{“Cables & Docks", "GDC", "Griffin DJ Cable", "$67”}},
  {{“Power Accessories", "UPA", "USB Power Adapter", "$76”}}};

string [ ] products = new string [3] string [ products ];
string [ ] productattributes = new string[3, 3];  string [ attributes, products];
string [ ]productcateogires = new string[3,1,4];  string [categories, products, attributes];
                   

Jagged Arrays:     
                                    Jagged Arrays are arrays within arrays. Jagged Arrays can have sub-arrays with different lengths. One can combine ‘n’ number of arrays with same dimensions which may have same length or different length.                     
Continuing with our products example we can combine ‘productscategories’ Array and ‘customerorder’ array by using a jagged array and the syntax is as follows:
string[,] customers = new string[3, 3] { { "GIFT", "Johny", "$42" }, { "GDC", "Mike", "$45" }, { "GDC", "Robin", "$24" } };

string [ ][,]customerorder = new string[2][,]{productattributes, customers};

Retrieving information from arrays:
                       
                        We can retrieve the information from the arrays by using the indexes. One can a for loop or foreach loop to retrieve information from the arrays.

Using for loop:
For example you can access the array information by using the following syntax:
string productcategory  = Productscategories[2,0,0];
string productattributes = productattribute[1,0];
Now by using for loop we can iterate through all the elements in the array as shown below:
For Loop for one dimensional array:
for (int i = 0; i < 3; i++)
            {
                Console.WriteLine("{0}",products[i]);
            }

For loop for two dimensional array:
  for( int i=0;i<3;i++)
            {
                for (int j = 0; j <3; j++)
                {
                    Console.WriteLine("{0}", productattributes[i, j]);
                }
                Console.WriteLine("================");
            }

For loop for three dimensional array:
for (int i = 0; i <2; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    for (int k = 0; k < 3; k++)
                    {
                        Console.WriteLine("{0}", customerorder[i][j, k]);
                    }
                    Console.WriteLine("================");
                }
            }
Instead of specifying the length of the array we can use the array.getlength() method as follows:

productattributes.GetLength (0) or productattributes (1) which returns the length of the arrays.

Using foreach loop:

To be more efficient in order to iterate through the collections, C# provides us with the foreach loop. With only one single line of code u can iterate through all the elements in the productattributes or productcateogries or customerorder. Foreach loop can be used as follows:

foreach(string s in productattributes)
            {
                Console.WriteLine("{0}", s);
            }
and
foreach(string s in productcateogries)
            {
                Console.WriteLine("{0}", s);
            }
and
foreach(string s in customerorder[0])
            {
                Console.WriteLine("{0}", s);
            }

Further Reading:
For all the methods and properties of the arrays you can visit the following link:
Most of the methods specified will work only for the single dimensional arrays and not for the multi-dimensional and jagged arrays.

No comments:

Post a Comment