Monday, September 10, 2012

Arrays Part -2


Array Class
Array class is the mother of all arrays and provides functionality for creating, manipulating, searching, and sorting arrays in .NET Framework.
 
Array class, defined in the System namespace, is the base class for arrays in C#. Array class is an abstract base class that means we cannot create an instance of the Array class.
 
Creating an Array
 
Array class provides the CreateInstance method to construct an array. The CreateInstance method takes first parameter as the type of items and second and third parameters are the dimension and their range. Once an array is created, we use SetValue method to add items to an array.
 
The following code snippet creates an array and adds three items to the array. As you can see the type of the array items is string and range is 3. You will get an error message if you try to add 4th item to the array.
 
Array stringArray = Array.CreateInstance(typeof(String), 3);
stringArray.SetValue("Mahesh Chand", 0);
stringArray.SetValue("Raj Kumar", 1);
stringArray.SetValue("Neel Beniwal", 2);
 
Note: Calling SetValue on an existing item of an array overrides the previous item value with the new value.
 
The code snippet in Listing 2 creates a multi-dimensional array.
 
Array intArray3D = Array.CreateInstance(typeof(Int32), 2, 3, 4);
for (int i = intArray3D.GetLowerBound(0); i <= intArray3D.GetUpperBound(0); i++)
    for (int j = intArray3D.GetLowerBound(1); j <= intArray3D.GetUpperBound(1); j++)
        for (int k = intArray3D.GetLowerBound(2); k <= intArray3D.GetUpperBound(2); k++)
        {
            intArray3D.SetValue((i * 100) + (j * 10) + k, i, j, k);
        }
 
foreach (int ival in intArray3D)
{
    Console.WriteLine(ival);
}
Listing 2
Array Properties
 
Table 1 describes Array class properties. 
 
IsFixedSize
Return a value indicating if an array has a fixed size or not.
IsReadOnly
Returns a value indicating if an array is read-only or not.
LongLength
Returns a 64-bit integer that represents total number of items in all the dimensions of an array.
Length
Returns a 32-bit integer that represents the total number of items in all the dimensions of an array.
Rank
Returns the number of dimensions of an array.
 
Table 1

The code snippet in Listing 3 creates an array and uses Array properties to display property values.
 
int[] intArray = new int[3] {0, 1, 2};
if(intArray.IsFixedSize)
{
    Console.WriteLine("Array is fixed size");
    Console.WriteLine("Size :" + intArray.Length.ToString());
    Console.WriteLine("Rank :" + intArray.Rank.ToString());
}
Listing 3
The output of Listing looks like Figure 2.
 
arrays2.png
Figure 2
Searching for an Item in an Array
The BinarySearch static method of Array class can be used to search for an item in an array. This method uses the binary search algorithm to search for an item. The method takes at least two parameters. First parameter is the array in which you would like to search and the second parameter is an object that is the item you are looking for. If an item is found in the array, the method returns the index of that item (based on first item as 0th item). Otherwise method returns a negative value.

Note: You must sort an array before searching. See comments in this article.

Listing 4 uses BinarySearch method to search an array for a string.
 
// Create an array and add 5 items to it
Array stringArray = Array.CreateInstance(typeof(String), 5);
stringArray.SetValue("Mahesh", 0);
stringArray.SetValue("Raj", 1);
stringArray.SetValue("Neel", 2);
stringArray.SetValue("Beniwal", 3);
stringArray.SetValue("Chand", 4);
 
// Find an item
object name = "Neel";
int nameIndex = Array.BinarySearch(stringArray, name);
if (nameIndex >= 0)
    Console.WriteLine("Item was at " + nameIndex.ToString() + "th position");
else
    Console.WriteLine("Item not found");
Listing 4
Sorting Items in an Array
The Sort static method of the Array class can be used to sort array items. This method has many overloaded forms. The simplest form takes as a parameter the array you want to sort. Listing 5 uses the Sort method to sort array items. Using the Sort method, you can also sort a partial list of items.
// Create an array and add 5 items to it
Array stringArray = Array.CreateInstance(typeof(String), 5);
stringArray.SetValue("Mahesh", 0);
stringArray.SetValue("Raj", 1);
stringArray.SetValue("Neel", 2);
stringArray.SetValue("Beniwal", 3);
stringArray.SetValue("Chand", 4);
 
// Find an item
object name = "Neel";
int nameIndex = Array.BinarySearch(stringArray, name);
if (nameIndex >= 0)
    Console.WriteLine("Item was at " + nameIndex.ToString() + "th position");
else
    Console.WriteLine("Item not found");
 
Console.WriteLine();
 
Console.WriteLine("Original Array");
Console.WriteLine("---------------------");
foreach (string str in stringArray)
{
    Console.WriteLine(str);
}
 
Console.WriteLine();
Console.WriteLine("Sorted Array");
Console.WriteLine("---------------------");
Array.Sort(stringArray);
foreach (string str in stringArray)
{
    Console.WriteLine(str);
}
Listing 5
The output of Listing 5 looks like Figure 3.
arrays3.png
Figure 3
Alternatively the Sort method takes starting index and number of items after that index. The following code snippet sorts 3 items starting at 2nd position.
Array.Sort(stringArray, 2, 3);

The new output looks like Figure 4.
arrays4.png
Figure 4
Getting and Setting Values
The GetValue and SetValue methods of the Array class can be used to get and set values of an array's items. The code listed in Listing 4 creates a 2-dimensional array instance using the CreateInstance method. After that I use the SetValue method to add values to the array. 
In the end, I find number of items in both dimensions and use GetValue method to read values and display on the console. 
Array names = Array.CreateInstance(typeof(String), 2, 4);
names.SetValue("Rosy", 0, 0);
names.SetValue("Amy", 0, 1);
names.SetValue("Peter", 0, 2);
names.SetValue("Albert", 0, 3);
names.SetValue("Mel", 1, 0);
names.SetValue("Mongee", 1, 1);
names.SetValue("Luma", 1, 2);
names.SetValue("Lara", 1, 3);
int items1 = names.GetLength(0);
int items2 = names.GetLength(1);
for (int i = 0; i < items1; i++)
    for (int j = 0; j < items2; j++)
        Console.WriteLine(i.ToString() + "," + j.ToString() + ": " + names.GetValue(i, j));
Listing 6
The output of Listing 6 generates Figure 5.
arrays5.png
Figure 5
Reverse an array items
The Reverse static method of the Array class reverses the order of items in an array. Similar to the Sort method, you can just pass an array as a parameter of the Reverse method. 
Array stringArray = Array.CreateInstance(typeof(String), 5);
stringArray.SetValue("Mahesh", 0);
stringArray.SetValue("Raj", 1);
stringArray.SetValue("Neel", 2);
stringArray.SetValue("Beniwal", 3);
stringArray.SetValue("Chand", 4);
           
Console.WriteLine("Original Array");
Console.WriteLine("---------------------");
foreach (string str in stringArray)
{
    Console.WriteLine(str);
}
 
Console.WriteLine();
Console.WriteLine("Reversed Array");
Console.WriteLine("---------------------");
Array.Reverse(stringArray);
//  Array.Sort(stringArray, 2, 3);
foreach (string str in stringArray)
{
    Console.WriteLine(str);
}
 
Console.WriteLine();
Console.WriteLine("Double Reversed Array");
Console.WriteLine("---------------------");
Array.Reverse(stringArray);
//  Array.Sort(stringArray, 2, 3);
foreach (string str in stringArray)
{
    Console.WriteLine(str);
}
Listing 7
The output of Listing 7 generates Figure 6.
 
arrays6.png
Figure 6
Clear an array items
The Clear static method of the Array class removes all items of an array and sets its length to zero. This method takes three parameters - first an array object, second starting index of the array and third is number of elements. The following code clears two elements from the array starting at index 1 (means second element of the array). 
Array.Clear(stringArray, 1, 2);
Note: Keep in mind, the Clear method does not delete items. Just clear the values of the items.
The code listed in Listing 8 clears two items from the index 1.
Array stringArray = Array.CreateInstance(typeof(String), 5);
stringArray.SetValue("Mahesh", 0);
stringArray.SetValue("Raj", 1);
stringArray.SetValue("Neel", 2);
stringArray.SetValue("Beniwal", 3);
stringArray.SetValue("Chand", 4);
Console.WriteLine("Original Array");
Console.WriteLine("---------------------");
foreach (string str in stringArray)
{
    Console.WriteLine(str);
}
 
Console.WriteLine();
Console.WriteLine("Clear Items");
Console.WriteLine("---------------------");
Array.Clear(stringArray, 1, 2);
 
foreach (string str in stringArray)
{
    Console.WriteLine(str);
}
Listing 8
The output of Listing 8 generates Figure 7. As you can see from Figure 7, the values of two items from the output are missing but actual items are there.
arrays7.png
Figure 7
Get the size of an array
The GetLength method returns the number of items in an array. The GetLowerBound and GetUppperBound methods return the lower and upper bounds of an array respectively. All these three methods take at least a parameter, which is the index of the dimension of an array. The following code snippet uses all three methods. 
Console.WriteLine(stringArray.GetLength(0).ToString());
Console.WriteLine(stringArray.GetLowerBound(0).ToString());
Console.WriteLine(stringArray.GetUpperBound(0).ToString()); 

Copy an array
The Copy static method of the Array class copies a section of an array to another array. The CopyTo method copies all the elements of an array to another one-dimension array. The code listed in Listing 9 copies contents of an integer array to an array of object types. 
// Creates and initializes a new Array of type Int32.
Array oddArray = Array.CreateInstance(Type.GetType("System.Int32"), 5);
oddArray.SetValue(1, 0);
oddArray.SetValue(3, 1);
oddArray.SetValue(5, 2);
oddArray.SetValue(7, 3);
oddArray.SetValue(9, 4);
// Creates and initializes a new Array of type Object.
Array objArray = Array.CreateInstance(Type.GetType("System.Object"), 5);
Array.Copy(oddArray, oddArray.GetLowerBound(0), objArray, objArray.GetLowerBound(0), 4);
int items1 = objArray.GetUpperBound(0);
for (int i = 0; i < items1; i++)
    Console.WriteLine(objArray.GetValue(i).ToString());
Listing 9
You can even copy a part of an array to another array by passing the number of items and starting item in the Copy method. The following format copies a range of items from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index.
public static void Copy(Array, int, Array, int, int);
Clone an Array
Clone method creates a shallow copy of an array. A shallow copy of an Array copies only the elements of the Array, whether they are reference types or value types, but it does not copy the objects that the references refer to. The references in the new Array point to the same objects that the references in the original Array point to.
The following code snippet creates a cloned copy of an array of strings.
string[] clonedArray = (string[])stringArray.Clone();

No comments:

Post a Comment