Add list to array C#

C# array a collection of objects or types. C# array elements can be of any type, including other array types. An array can be Single-Dimensional, Multidimensional, or Jagged. The Array class in C# represents an array. This tutorial is an introduction to array and how to use arrays in C#. The tutorial also discusses various methods and properties of C# Array class.

In C#, an array index starts at zero. That means the first item of an array starts at the 0th position. The position of the last item on an array will the total number of items - 1. So if an array has 10 items, the last 10th item is in 9th position.

In C#, arrays can be declared as fixed-length or dynamic. A fixed-length array can store a predefined number of items. A dynamic array does not have a predefined size. The size of a dynamic array increases as you add new items to the array. You can declare an array of fixed length or dynamic. You can even change a dynamic array to static after it is defined.

Let's take a look at simple declarations of arrays in C#. The following code snippet defines the simplest dynamic array of integer types that do not have a fixed size.

int[] intArray;

As you can see from the above code snippet, the declaration of an array starts with a type of array followed by a square bracket [[]] and the name of the array.

The following code snippet declares an array that can store 5 items only starting from index 0 to 4.

int[]intArray; intArray=newint[5];

The following code snippet declares an array that can store 100 items starting from index 0 to 99.

int[]intArray; intArray=newint[100];

Arrays types in C#

In the previous code snippet, we saw how to define a simple array of integer type. Similarly, we can define arrays of any type such as double, character, and string.

In C#, arrays are objects. That means that declaring an array doesn't create an array. After declaring an array, you need to instantiate an array by using the "new" operator.

The following code snippet defines arrays of double, char, bool, and string data types.

double[]doubleArray=newdouble[5]; char[]charArray=newchar[5]; bool[]boolArray=newbool[2]; string[]stringArray=newstring[10];

Initializing Array in C#

Once an array is declared, the next step is to initialize an array. The initialization process of an array includes adding actual data to the array.

The following code snippet creates an array of 3 items and values of these items are added when the array is initialized.

//Initializeafixedarray int[]staticIntArray=newint[3]{1,3,5};

Alternative, we can also add array items one at a time as listed in the following code snippet.

//Initializeafixedarrayoneitematatime int[]staticIntArray=newint[3]; staticIntArray[0]=1; staticIntArray[1]=3; staticIntArray[2]=5;

The following code snippet declares a dynamic array with string values.

//Initializeadynamicarrayitemsduringdeclaration string[]strArray=newstring[]{"MaheshChand","MikeGold","RajBeniwal","PraveenKumar","DineshBeniwal"};

Accessing Array in C#

We can access an array item by passing the item index in the array. The following code snippet creates an array of three items and displays those items on the console.

//Initializeafixedarrayoneitematatime int[]staticIntArray=newint[3]; staticIntArray[0]=1; staticIntArray[1]=3; staticIntArray[2]=5; //Readarrayitemsonebyone Console.WriteLine[staticIntArray[0]]; Console.WriteLine[staticIntArray[1]]; Console.WriteLine[staticIntArray[2]];

This method is useful when you know what item you want to access from an array. If you try to pass an item index greater than the items in array, you will get an error.

Accessing a C# array using a foreach Loop

The foreach control statement [loop] is used to iterate through the items of an array. For example, the following code uses foreach loop to read all items of an array of strings.

//Initializeadynamicarrayitemsduringdeclaration string[]strArray=newstring[]{ "MaheshChand", "MikeGold", "RajBeniwal", "PraveenKumar", "DineshBeniwal" }; //Readarrayitemsusingforeachloop foreach[stringstrinstrArray]{ Console.WriteLine[str]; }

This approach is used when you do not know the exact index of an item in an array and needs to loop through all the items.

Array Types in C#

Arrays can be divided into the following four categories.

  • Single-dimensional arrays
  • Multidimensional arrays or rectangular arrays
  • Jagged arrays
  • Mixed arrays.

Single Dimension Arrays

Single-dimensional arrays are the simplest form of arrays. These types of arrays are used to store the number of items of a predefined type. All items in a single dimension array are stored contiguously starting from 0 to the size of the array -1.

The following code declares an integer array that can store 3 items. As you can see from the code, first I declare the array using [] bracket and after that, I instantiate the array by calling the new operator.

int[]intArray; intArray=newint[3];

Array declarations in C# are pretty simple. You put array items in curly braces [{}]. If an array is not initialized, its items are automatically initialized to the default initial value for the array type if the array is not initialized at the time it is declared.

The following code declares and initializes an array of three items of integer type.

int[]staticIntArray=newint[3]{1,3,5};

The following code declares and initializes an array of 5 string items.

string[]strArray=newstring[5]{"Mahesh","Mike","Raj","Praveen","Dinesh"};

You can even directly assign these values without using the new operator.

string[]strArray={"Mahesh","Mike","Raj","Praveen","Dinesh"};

You can initialize a dynamic length array as follows.

string[]strArray=newstring[]{"Mahesh","Mike","Raj","Praveen","Dinesh"};

Multi-Dimensional Arrays in C#

A multi-dimensional array, also known as a rectangular array is an array with more than one dimension. The form of a multi-dimensional array is a matrix.

Declaring a multi-dimensional array

A multi-dimension array is declared as follows:

string[,] mutliDimStringArray;

A multi-dimensional array can be fixed-sized or dynamic sized.

Initializing multi-dimensional arrays

The following code snippet is an example of fixed-sized multi-dimensional arrays that defines two multi dimension arrays with a matrix of 3x2 and 2x2. The first array can store 6 items and second array can store 4 items. Both of these arrays are initialized during the declaration.

int[,]numbers=newint[3,2]{{1,2},{3,4},{5,6}}; string[,]names=newstring[2,2]{{"Rosy","Amy"},{"Peter","Albert"}};

Now let's see examples of multi-dimensional dynamic arrays where you are not sure of the number of items of the array. The following code snippet creates two multi-dimensional arrays with no limit.

int[,]numbers=newint[,]{{1,2},{3,4},{5,6}}; string[,]names=newstring[,]{{"Rosy","Amy"},{"Peter","Albert"}};

You can also omit the new operator as we did in single dimension arrays. You can assign these values directly without using the new operator. For example:

int[,]numbers={ { 1, 2 }, { 3, 4 }, { 5, 6 } }; string[,]names={ { "Rosy", "Amy" }, { "Peter", "Albert" } };

We can also initialize the array items one item at a time. The following code snippet is an example of initializing array items one at a time.

int[,]numbers=newint[3,2]; numbers[0,0]=1; numbers[1,0]=2; numbers[2,0]=3; numbers[0,1]=4; numbers[1,1]=5; numbers[2,1]=6;

Accessing multi-dimensional arrays

Multi-dimensional array items are represented in a matrix format and to access its items, we need to specify the matrix dimension. For example, item[1,2] represents an array item in the matrix in the second row and third column.

The following code snippet shows how to access numbers array defined in the above code.

Console.WriteLine[numbers[0,0]]; Console.WriteLine[numbers[0,1]]; Console.WriteLine[numbers[1,0]]; Console.WriteLine[numbers[1,1]]; Console.WriteLine[numbers[2,0]]; Console.WriteLine[numbers[2,2]];

Jagged Arrays in C#

Jagged arrays are arrays of arrays. The elements of a jagged array are other arrays.

Declaring Jagged Arrays

Declaration of a jagged array involves two brackets. For example, the following code snippet declares a jagged array that has three items of an array.

int[][] intJaggedArray = new int[3][];

The following code snippet declares a jagged array that has two items of an array.

string[][] stringJaggedArray = new string[2][];

Initializing Jagged Arrays

Before a jagged array can be used, its items must be initialized. The following code snippet initializes a jagged array; the first item with an array of integers that has two integers, second item with an array of integers that has 4 integers, and the third item with an array of integers that has 6 integers.

//Initializingjaggedarrays intJaggedArray[0]=newint[2]; intJaggedArray[1]=newint[4]; intJaggedArray[2]=newint[6];

We can also initialize a jagged array's items by providing the values of the array's items. The following code snippet initializes item an array's items directly during the declaration.

//Initializingjaggedarrays intJaggedArray[0]=newint[2]{ 2, 12 }; intJaggedArray[1]=newint[4]{ 4, 14, 24, 34 }; intJaggedArray[2]=newint[6]{ 6, 16, 26, 36, 46, 56 };

Accessing Jagged Arrays

We can access a jagged array's items individually in the following way:

Console.Write[intJaggedArray3[0][0]]; Console.WriteLine[intJaggedArray3[2][5]];

We can also loop through all of the items of a jagged array. The Length property of an array helps a lot; it gives us the number of items in an array. The following code snippet loops through all of the items of a jagged array and displays them on the screen.

//Loopthroughallitesmofajaggedarray for[inti=0;i

Chủ Đề