C# arrays

xingyun86 2021-5-30 785

In this part of the C# programming tutorial, we cover arrays.

C# array definition

An  is a collection of data. A scalar variable can hold only one item at a time. Arrays can hold multiple items. These items are called elements of the array. Arrays store data of the same data type. Each element can be referred to by an index. Arrays are zero based. The index of the first element is zero. Arrays are reference types.

Arrays are used to store data of our applications. We declare arrays to be of a certain data type. We specify their length. And we initialize arrays with data. We have several methods for working with arrays. We can modify the elements, sort them, copy them or search for them.

int[] ages;
String[] names;
float[] weights;

We have three array declarations. The declaration consists of two parts. The type of the array and the array name. The type of an array has a data type that determines the types of the elements within an array (intStringfloat in our case) and a pair of square brackets []. The brackets indicate that we have an array.

Collections serve the similar purpose. They are more powerful than arrays. They will be described later in a separate chapter.

C# initializing arrays

There are several ways, how we can initialize an array in C#.

Program.cs
using System;

int[] array = new int[5];

array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;
array[4] = 5;

for (int i = 0; i < array.Length; i++)
{
    Console.WriteLine(array[i]);
}

We declare and initialize a numerical array. The contents of the array are printed to the console.

int[] array = new int[5];

Here we declare an array which contains five elements. All elements are integers.

array[0] = 1;
array[1] = 2;
...

We initialize the array with some data. This is assignment initialization. The indexes are in the square brackets. Number 1 is going to be the first element of the array, 2 the second.

for (int i = 0; i < array.Length; i++)
{
    Console.WriteLine(array[i]);
}

We go through the array and print its elements. An array has a Length property, which gives the number of elements in the array. Since arrays are zero based, the indexes are 0..length-1.

We can declare and initialize an array in one statement.

Program.cs
using System;

int[] array = new int[] { 2, 4, 5, 6, 7, 3, 2 };

foreach (int i in array)
{
    Console.WriteLine(i);
}

This is a modified version of the previous program.

int[] array = new int[] {2, 4, 5, 6, 7, 3, 2 };

An array is declared and initialized in one step. The elements are specified in the curly brackets. We did not specify the length of the array. The compiler will do it for us.

foreach (int i in array)
{
    Console.WriteLine(i);
}

We use the foreach keyword to traverse the array and print its contents.

C# array accessing elements

After an array is created, its elements can be accessed by their index. The index is a number placed inside square brackets which follow the array name.

We can use the index from end ^ operator to get elements from the end of the array. The ^0 equals to array.Length and the ^n to array.Length - n.

Program.cs
using System;

string[] names = { "Jane", "Thomas", "Lucy", "David" };

Console.WriteLine(names[0]);
Console.WriteLine(names[1]);
Console.WriteLine(names[2]);
Console.WriteLine(names[3]);

Console.WriteLine("*************************");

Console.WriteLine(names[^1]);
Console.WriteLine(names[^2]);
Console.WriteLine(names[^3]);
Console.WriteLine(names[^4]);

In the example, we create an array of string names. We access each of the elements by its index and print them to the terminal.

string[] names = { "Jane", "Thomas", "Lucy", "David" };

An array of strings is created.

Console.WriteLine(names[0]);
Console.WriteLine(names[1]);
Console.WriteLine(names[2]);
Console.WriteLine(names[3]);

Each of the elements of the array is printed to the console. With the names[0] construct, we refer to the first element of the names array.

Console.WriteLine(names[^1]);
Console.WriteLine(names[^2]);
Console.WriteLine(names[^3]);
Console.WriteLine(names[^4]);

We access array elements from the end.

$ dotnet run
Jane
Thomas
Lucy
David
*************************
David
Lucy
Thomas
Jane

C# array modify elements

It is possible to modify the elements of an array - they are not immutable.

Program.cs
using System;

int[] vals = { 1, 2, 3, 4 };

vals[0] *= 2;
vals[1] *= 2;
vals[2] *= 2;
vals[3] *= 2;

Console.WriteLine("[{0}]", string.Join(", ", vals));

We have an array of three integers. Each of the values will be multiplied by two.

int[] vals = { 1, 2, 3, 4 };

An array of three integers is created.

vals[0] *= 2;
vals[1] *= 2;
vals[2] *= 2;
vals[3] *= 2;

Using the element access, we multiply each value in the array by two.

Console.WriteLine("[{0}]", string.Join(", ", vals));

With the Join method, we create one string from all elements of the array. The elements are separated with a comma character.

$ dotnet run
[2, 4, 6, 8]

All four integers have been multiplied by number 2.

C# array slices

We can use the .. operator to get array slices. A range specifies the start and end of a range. The start of the range is inclusive, but the end of the range is exclusive. It means that the start is included in the range but the end is not included in the range.

Program.cs
using System;

int[] vals = { 1, 2, 3, 4, 5, 6, 7 };

int[] vals2 = vals[1..5];
Console.WriteLine("[{0}]", string.Join(", ", vals2));

int[] vals3 = vals[..6];
Console.WriteLine("[{0}]", string.Join(", ", vals3));

int[] vals4 = vals[3..];
Console.WriteLine("[{0}]", string.Join(", ", vals4));

The example works with array ranges.

int[] vals2 = vals[1..5];

We create an array slice containing elements from index 1 to index 4.

int[] vals3 = vals[..6];

If the start index is omitted, the slice starts from index 0.

int[] vals4 = vals[3..];

If the end index is omitted, the slice goes until the end of the array.

$ dotnet run
[2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]
[4, 5, 6, 7]

C# traversing arrays

We often need to go through all elements of an array. We show two common methods for traversing an array.

Program.cs
using System;

string[] planets = { "Mercury", "Venus", "Mars",
    "Earth", "Jupiter",  "Saturn", "Uranus", "Neptune", "Pluto" };

for (int i=0; i < planets.Length; i++)
{
    Console.WriteLine(planets[i]);
}

foreach (string planet in planets)
{
    Console.WriteLine(planet);
}

An array of planet names is created. We use the for and foreach statements to print all the values.

for (int i=0; i < planets.Length; i++)
{
    Console.WriteLine(planets[i]);
}

In this loop, we utilize the fact that we can get the number of elements from the array object. The number of elements is stored in the Length property.

foreach (string planet in planets)
{
    Console.WriteLine(planet);
}

The foreach statement can be used to make the code more compact when traversing arrays or other collections. In each cycle, the planet variable is passed the next value from the planets array.

C# array dimensions

So far, we have worked with one-dimensional arrays. The number of indexes needed to specify an element is called the dimension, or rank of the array.

Two-dimensional array

Next, we will work with two-dimensional array.

Program.cs
using System;

int[,] twodim = new int[,] { {1, 2, 3}, {1, 2, 3}  };

int d1 = twodim.GetLength(0);
int d2 = twodim.GetLength(1);

for (int i=0; i<d1; i++)
{
    for (int j=0; j<d2; j++)
    {
        Console.WriteLine(twodim[i, j]);
    }
}

If we need two indexes to access an element in an array then we have a two dimensional array.

int[,] twodim = new int[,] { {1, 2, 3}, {1, 2, 3}  };

We declare and initialize a two dimensional array in one statement. Note the comma inside the square brackets.

int d1 = twodim.GetLength(0);
int d2 = twodim.GetLength(1);

We get the dimensions of the array. The GetLength gets the number of elements in the specified dimension of the array.

for (int i=0; i<d1; i++)
{
    for (int j=0; j<d2; j++)
    {
        Console.WriteLine(twodim[i, j]);
    }
}

We use two for loops to go through all the elements of a two dimensional array. Note that a specific array element is obtained using two indexes, separated by a comma character.

$ dotnet run
1
2
3
1
2
3

We can traverse a two-dimensional array with the foreach loop.

Program.cs
using System;

int[,] vals = new int[4, 2]
{
    { 9, 99 },
    { 3, 33 },
    { 4, 44 },
    { 1, 11 }
};

foreach (var val in vals)
{
    Console.WriteLine(val);
}

With the foreach loop, we get the elements one-by-one from the beginning to the end.

$ dotnet run
9
99
3
33
4
44
1
11

Three-dimensional array

Next, we work with a three dimensional array.

Program.cs
using System;


int[,,] n3 =
{
    {{12, 2, 8}},
    {{14, 5, 2}},
    {{3, 26, 9}},
    {{4, 11, 2}}
};

int d1 = n3.GetLength(0);
int d2 = n3.GetLength(1);
int d3 = n3.GetLength(2);

for (int i=0; i<d1; i++)
{
    for (int j=0; j<d2; j++)
    {
        for (int k=0; k<d3; k++)
        {
            Console.Write(n3[i, j, k] + " ");
        }
    }
}

Console.Write('\n');

We have a numerical three-dimensional array. Again, we initialize the array with numbers and print them to the terminal.

int[,,] n3 = {
    {{12, 2, 8}},
    {{14, 5, 2}},
    {{3, 26, 9}},
    {{4, 11, 2}}
};

There is another comma between the square brackets on the left side and additional curly brackets on the right side.

for (int k=0; k<d3; k++)
{
    Console.Write(n3[i, j, k] + " ");
}

This loop goes through the third dimension. We use three indexes to retrieve the value from the array.

$ dotnet run
12 2 8 14 5 2 3 26 9 4 11 2

C# Rank

There is a Rank property which gives the number of dimensions of an array.

Program.cs
using System;

int[]   a1 = { 1, 2 };
int[,]  a2 = { { 1 }, { 2 } };
int[,,] a3 = { { { 1, 2 }, { 2, 1 } } };

Console.WriteLine(a1.Rank);
Console.WriteLine(a2.Rank);
Console.WriteLine(a3.Rank);

We have three arrays. We use the Rank property to get the number of dimensions for each of them.

Console.WriteLine(a1.Rank);

Here we get the rank for the first array.

$ dotnet run
1
2
3

C# jagged arrays

Arrays that have elements of the same size are called rectangular arrays. In contrast, arrays which have elements of different size are called jagged arrays. Jagged arrays are declared and initialized differently.

Program.cs
using System;

int[][] jagged = new int[][]
{
    new int[] { 1, 2 },
    new int[] { 1, 2, 3 },
    new int[] { 1, 2, 3, 4 }
};

foreach (int[] array in jagged)
{
    foreach (int e in array)
    {
        Console.Write(e + " ");
    }
}

Console.Write('\n');

This is an example of a jagged array.

int[][] jagged = new int[][]
{
    new int[] { 1, 2 },
    new int[] { 1, 2, 3 },
    new int[] { 1, 2, 3, 4 }
};

This is a declaration and initialization of a jagged array. Note that this time, we use two pairs of square brackets. We have an array of arrays. More specifically, we have declared an array to have three arrays of int data type. Each of the arrays has different number of elements.

foreach (int[] array in jagged)
{
    foreach (int e in array)
    {
        Console.Write(e + " ");
    }
}

We use two foreach loops to traverse the jagged array. In the first loop, we get the array. In the second loop, we get the elements of the obtained array.

C# array methods

There are various methods for working with arrays. These methods can be used for retrieving, modifying, sorting, copying, searching data. These methods that we use are static methods of the Array class or member methods of the array objects.

Program.cs
using System;

string[] names = {"Jane", "Frank", "Alice", "Tom" };

Array.Sort(names);

foreach(string el in names)
{
    Console.Write(el + " ");
}

Console.Write('\n');

Array.Reverse(names);

foreach(string el in names)
{
    Console.Write(el + " ");
}

Console.Write('\n');

In this example, we sort the data.

string[] names = {"Jane", "Frank", "Alice", "Tom" };

We have an array of strings.

Array.Sort(names);

The static Sort method sorts the data alphabetically.

Array.Reverse(names);

The Reverse method reverses the sequence of the elements in the entire one-dimensional array.

$ dotnet run
Alice Frank Jane Tom
Tom Jane Frank Alice

We have ordered the names in ascending and descending order.

The following example uses SeValueGetValueIndexOfCopy and Clear methods.

Program.cs
using System;

string[] names = {"Jane", "Frank", "Alice", "Tom"};
string[] girls = new string[5];

names.SetValue("Beky", 1);
names.SetValue("Erzebeth", 3);

Console.WriteLine(names.GetValue(1));
Console.WriteLine(names.GetValue(3));

Console.WriteLine(Array.IndexOf(names, "Erzebeth"));

Array.Copy(names, girls, names.Length);

foreach(string girl in girls)
{
    Console.Write(girl + " ");
}

Console.Write('\n');

Array.Clear(names, 0, 2);

foreach(string name in names)
{
    Console.Write(name + " ");
}

Console.Write('\n');

This example introduces additional methods.

names.SetValue("Beky", 1);
names.SetValue("Erzebeth", 3);

The SetValue sets a value for a specific index in the array.

Console.WriteLine(names.GetValue(1));
Console.WriteLine(names.GetValue(3));

We retrieve the values from the array with the GetValue method.

Console.WriteLine(Array.IndexOf(names, "Erzebeth"));

The IndexOf method returns an index for the first occurrence of a specific value.

Array.Copy(names, girls, names.Length);

The Copy method copies values from the source array to the destination array. The first parameter is the source array, the second is the destination array. The third parameter is the length; it specifies the number of elements to copy.

Array.Clear(names, 0, 2);

The Clear method removes all elements from the array. It takes three parameters: the array, the start index and the number of elements from the index to clear.

$ dotnet run
Beky
Erzebeth
3
Jane Beky Alice Erzebeth
  Alice Erzebeth

In this part of the C# tutorial, we have worked with arrays.


×
打赏作者
最新回复 (0)
只看楼主
全部楼主
返回