The previous chapter explained how to create 2-dimensional, 3-dimensional, and jagged arrays in C#. In this chapter, we will explore how to access, remove, and sort the elements of an array.
Getting the number of dimensions of an array
The number of dimensions of an array can be obtained via the Rank
property of the array. For example:
char[,] my2Darray = new char[3,3] { {'a', 'b', 'c'}, {'c', 'd', 'e'}, {'c', 'd', 'e'} }; char[,,] my3Darray = // new char[2,2,3] { { { 'a', 'b', 'c' }, { 'c', 'd', 'e' } }, { { 'f', 'g', 'h' }, { 'i', 'j', 'k' } } }; System.Console.WriteLine($"Dimensions in my2Darray = {my2Darray.Rank}"); System.Console.WriteLine($"Dimensions in my3Darray = {my3Darray.Rank}");
Output:
Dimensions in my2Darray = 2
Dimensions in my3Darray = 3
Accessing array elements
Once values have been stored in an array, it is highly likely that these values will need to be accessed at some later point in the C# code. This is achieved using the array accessor notation combined with the index into the array of the desired value. The array accessor is simply the array name followed by square brackets ([]). Within the square brackets is placed a number representing the index into the array of the desired value (keeping in mind that the first array element in C# is index 0). For example, to access the second element of our myColors array, the following notation would be used:
string[] myColors = {"red", "green", "yellow", "orange", "blue"}; System.Console.WriteLine($"Element at index 1 = {myColors[1]}");
When executed, the above code will output the word “green” since this is the string contained at index position 1 in the array.
Similarly, the value at a particular index position in an array may be changed using the accessor notation combined with the assignment operator (=
). For example, to change the value of the first item in the array:
string[] myColors = {"red", "green", "yellow", "orange", "blue"}; myColors[0] = "violet"; System.Console.WriteLine($"Element at index 0 = {myColors[0]}");
Values in a multidimensional array may be accessed by specifying the index values for each dimension separated by commas. For example, to access the first element of the first array of our my2Darray
the following accessor would be used (keeping in mind that arrays start at index position 0):
char element = my2Darray[0,0];
The following code demonstrates accessing a variety of elements, both in 2D and 3D arrays:
char[,] my2Darray = new char[3,3] { {'a', 'b', 'c'}, {'d', 'e', 'f'}, {'g', 'h', 'i'} }; char[,,] my3Darray = { { { 'a', 'b', 'c' }, { 'd', 'e', 'f' } }, { { 'g', 'h', 'i' }, { 'j', 'k', 'l' } } }; // Output first element of first array in my2Darray System.Console.WriteLine($"{my2Darray[0,0]}"); // Output last element of last array in my2Darray System.Console.WriteLine($"{my2Darray[2,2]}"); // Output 2nd element of 2nd array in 1st 2D array of my3Darray System.Console.WriteLine($"{my3Darray[0,1,1]}"); // Output 3rd element of 2nd array in 2nd 2D array of my3Darray System.Console.WriteLine($"{my3Darray[1,1,2]}");
Output:
a
i
e
l
Array iteration
The easiest way to iterate through the items in an array is to make use of the foreach
looping syntax. The following code, for example, iterates through all of the items in an array and outputs each item to the console panel:
string[] myColors = {"red", "green", "yellow", "orange", "blue"}; foreach (string color in myColors) { System.Console.Write("{0} ", color); }
Output:
red green yellow orange blue
You can also use the foreach
statement to iterate through multidimensional arrays. In the following example, we use foreach
to iterate through all the elements of a three-dimensional array:
char[,,] my3Darray = { { { 'a', 'b', 'c' }, { 'c', 'd', 'e' } }, { { 'f', 'g', 'h' }, { 'i', 'j', 'k' } } }; foreach (char letter in my3Darray) { System.Console.Write("{0} ", letter); }
Output:
a b c c d e f g h i j k
Working with ranges
The C# range (..
) and index from end (^
) operators are particularly useful for accessing subsets of array elements. Ranges are constructed using the following syntax where x
and y
represent the beginning and end range values, respectively:
x..y
Note: When working with ranges, it is important to remember that range syntax x..y
encompasses all the numbers from x
up to, but not including, y
. The range operator 5…8, therefore, specifies the positions 5, 6, and 7.
In the absence of start or end positions, the range will include all possible values starting at 0 until the end of the array is reached:
..
One-sided range operators specify a range that can extend as far as possible in a specified range direction until the natural beginning or end of the range is reached (or until some other condition is met). A one-sided range is declared by omitting the number from one side of the range declaration, for example:
x…
or
…y
A range to specify two elements in an array starting with position 2 through to the last element could be declared as follows:
2…
Similarly, to specify a range that begins with the first element and ends with the element at position 5, the range would be specified as follows:
…6
The following example extracts items 4 through 6 and assigns them to a new array named words
:
string[] sentence = {"The", "best", "way", "to", "predict", "the", "future", "is", "to", "invent", "it"}; string[] words = sentence[4..7];
Similarly, we can use the following range syntax to extract words starting at element 0 and ending at element 4 follows:
string[] words = sentence[..5];
We can also combine the index operator with the range operator to perform operations similar to the following which extract elements starting at position 1 up until the second from last element of the array:
string[] words = sentence[1..^2];
Try the following code to see the above examples in action:
string[] sentence = {"The", "best", "way", "to", "predict", "the", "future", "is", "to", "invent", "it"}; string[] subset1 = sentence[^7..^4]; string[] subset2 = sentence[..^2]; string[] subset3 = sentence[3..^3]; foreach (string word in subset1) { System.Console.Write("{0} ", word); } System.Console.WriteLine("\n"); foreach (string word in subset2) { System.Console.Write("{0} ", word); } System.Console.WriteLine("\n"); foreach (string word in subset3) { System.Console.Write("{0} ", word); }
When the above code runs, it will generate the following output:
predict the future
The best way to predict
The best way to predict the future is to invent it
C# index from end operator
The C# index from end (^
) operator allows you to specify the end of a range based on the number of positions from the end of the array.
The index ^1
, for example, represents the last item in the array, ^2
the second from last item in the array, and so on. Index ^0
is already set to the total number of items in the array:
string[] myArray = { "item 1", // <-- ^7 - 7th from last "item 2", // <-- ^6 "item 3", // <-- ^5 "item 4", // <-- ^4 "item 5", // <-- ^3 "item 6", // <-- ^2 "item 7" // <-- ^1 - Last item // ^0 = array length };
The following code demonstrates the use of the index operator when working with ranges and arrays:
string[] sentence = {"The", "best", "way", "to", "predict", "the", "future", "is", "to", "invent", "it"}; string[] subset1 = sentence[^7..^4]; string[] subset2 = sentence[..^2]; string[] subset3 = sentence[3..^3]; foreach (string word in subset1) { System.Console.Write("{0} ", word); } System.Console.WriteLine("\n"); foreach (string word in subset2) { System.Console.Write("{0} ", word); } System.Console.WriteLine("\n"); foreach (string word in subset3) { System.Console.Write("{0} ", word); }
Output:
predict the future
The best way to predict the future is to
to predict the future is
Sorting C# arrays
The C# array is part of the System.Array
package, which also includes some useful methods for sorting and re-ordering arrays.
If you need to sort an array, pass it as an argument to the Sort()
method as follows:
string[] myColors = { "red", "green", "yellow", "orange", "blue" }; System.Console.WriteLine("Before Sort"); foreach (string color in myColors) { System.Console.Write("{0} ", color); } System.Array.Sort(myColors); System.Console.WriteLine("\n\nAfter Sort"); foreach (string color in myColors) { System.Console.Write("{0} ", color); }
Output:
Before Sort
red green yellow orange blue
After Sort
blue green orange red yellow
You can also reverse the order of the elements in an array using the System.Array.Reverse()
method:
string[] myColors = {"red", "green", "yellow", "orange", "blue"}; System.Array.Reverse(myColors); foreach (string color in myColors) { System.Console.Write("{0} ", color); }
Output:
blue orange yellow green red
Clearing C# arrays
The values in an array may be cleared using the System.Array.Clear()
method. This method clears each item in an array to the default value for the type (false
for Boolean values, 0 for numeric items, and null
for strings). The syntax for clearing array elements is as follows:
System.Array.Clear(<array>, <start index>, <count>);
In the above syntax, <array> is the array to be cleared, <start index> is the position within the array at which clearing is to begin, and <count> is the number of elements to be cleared.
The following example clears three elements starting at item 1:
string[] myColors = {"red", "green", "yellow", "orange", "blue"}; System.Array.Clear(myColors, 1, 3); foreach (string color in myColors) { System.Console.Write("{0} ", color); }
When the above code runs, only the blue and red elements will remain in the array.