Arrays and Lists in C#

One of the major tasks of a computer program is to process a collection of data. Be it in the form of a collection of records that are to be stored in the database or collection of bytes to be received over some network. Consider a scenario where you have to store records of all the items sold in a day. The items sold can be in the thousands. In such scenarios, it is not appropriate to create a thousand string type variables to store the names of the sold items. Rather a collection that can hold a thousand records is more suitable.

Arrays and Lists are data structures that store data in the form of collections. In this article, we will see what arrays and lists are, how they are initialized, how we can store data in them, how to access data within arrays and lists, and what are some of most useful array and list functions.

Arrays

Arrays are used to store a collection of data of the same type. Owing to its strongly-typed nature arrays can store a collection of multiple integers, strings or any other data type. However, one array cannot store collections of strings as well as integers. There is virtually no upper limit to the size of an array. You can store as many items as you want in an array. Another important thing about arrays is that they are immutable, meaning, once initialized they cannot be changed. For example, you cannot increase or decrease the size of the array.

Enough of theory. Let’s have a look at different ways to initialize arrays in C#

string[] countries = new string[5];
countries[0] = "England";
countries[1] = "USA";
countries[2] = "Canada";
countries[3] = "Russia";
countries[4] = "France";

foreach (string country in countries)
{
	Console.WriteLine(country);
}

In the

above example a string type array “countries” has been initialized. The array can contain five items. To declare an array variable write the type of the array followed by opening and closing brackets and the name of the array. To initialize an array use “new” keyword followed by the array type and the number of items the array can hold. The number of items is specified inside opening and closing square brackets.

Now to access the first index, you have to write the name of the array followed by index number within square brackets. For instance, to access the first country name, you write countries[0]. It is appropriate to mention here that array index starts from zero. This means that the first element of the array is located at 0th index while the last element is located at n-1st index where n is the size of the array.

The best way to iterate through an array is via a foreach loop. Take a look at the above example to see how foreach loop is being used to display all the country names within countries array.

Arrays can also be initialized directly without “new” keyword.

string[] countries = { "England", "USA", "Russia", "Canada", "France" };

foreach (var country in countries)
{
	Console.WriteLine(country);
}

Simply add array items inside the curly brackets where a comma separates each item. The size of the array is calculated at runtime.

Multidimensional Arrays

The arrays created in the previous examples are one-dimensional. You can also create arrays of arrays. Such arrays are called multidimensional arrays. Take a look at the following example to see how a multidimensional array is created.

string[,] countries = new string[2, 3];
countries[0, 0] = "USA";
countries[0, 1] = "England";
countries[0, 2] = "France";
countries[1, 0] = "Germany";
countries[1, 1] = "Canada";
countries[1, 2] = "Russia";

for (int i = 0; i < 2; i++)
{
	for (int j = 0; j < 3; j++)
	{
		Console.WriteLine(countries[i,j] + " ");
	}
	Console.WriteLine();
}

In the above example, a multidimensional array with two rows and three columns has been created. This array can store a total of 6 elements, three in each row. To create a multidimensional array you have to specify the size of each dimension separated by a comma within the opening and closing square brackets. For instance, if you want to create a multidimensional array of seven rows and 10 columns you specify it within brackets as [7, 10].

Array Methods

You can use static Array class to perform different functions on C# array. Take a look at the following example to see how Array class can be used to reverse an array.

string[] countries = { "America", "China", "Russia", "England" };

foreach (var country in countries)
{
	Console.WriteLine(country);
}

Array.Reverse(countries);

foreach (var country in countries)
{
	Console.WriteLine(country);
}

If you run the above code, you shall see the names of the countries in the order you added them in countries array. After that you will see countries name in reverse order, this is because before traversing through the countries array again, the array is reversed.

Lists

Lists are also used to store collections of data. However, lists unlike arrays, are mutable. You can add or remove items from the list at runtime. Also, since lists implement the IEnumerable<T> and IEnumerable interface, you can execute LINQ queries on lists. Lists belong to System.Collections.Generic namespace. Take a look at the following example to see how lists are created in C#.

// Creating a list
List<string> countries = new List<string>();

// Adding elements to list

countries.Add("England");
countries.Add("China");
countries.Add("USA");
countries.Add("Russia");

foreach (var country in countries)
{
	Console.WriteLine(country);
}

In the above code, you see that the size of the list is not defined at the time of initialization. You can add as many items as you want via the “Add” method. You can also remove items via the “Remove’ method. Like arrays, you can add elements to a list at the time of initialization. Take a look at the following example.

List<string> countries = new List<string>() { "America", "China", "Russia", "England" };

foreach (string country in countries)
{
	Console.WriteLine(country);
}

Lists have many built-in functions that are extremely useful. For instance if you want to find the first and last item in a list you can use First() and Last() methods. Similarly, you can easily clear a list via Clear() function. Take a look at the following example to see these methods in action.

List<string> countries = new List<string>() { "America", "China", "Russia", "England" };

Console.WriteLine(countries.First());
Console.WriteLine(countries.Last());
countries.Clear();
Console.WriteLine(countries.Count);

If you run the above code, you will see that “America” and “England” being the first and last items in the list will be printed on the console. Next, the countries list has been cleared. Now if you print the count of the items in the countries list, you shall see that zero will be printed on the screen.

LINQ

Finally, you can execute LINQ queries on Lists. LINQ stands for language integrated query and is commonly used for querying databases. It can also be used to query local collections. For instance using a LINQ query, we can print only those items from countries list that contain a letter “e” in them. Take a look at the following example.

List<string> countries = new List<string>()("America", "China", "Russia", "England");

IEnumerable<string> countries2 = countries.Where(x => x.ToLower().Contains("e"));
foreach (var country in countries2)
{
	Console.WriteLine(country);
}

If you execute the above code, you will see that only America and England will be printed on the console. This is due to these are the only countries in the list with a letter “e”.

This article presents a brief introduction to some of the most fundamental concepts related to usage arrays and lists in C#. As always, if you have any questions or comments be sure to leave a comment below.