C# Basic – Lesson 4: Arrays and Lists

Hi and welcome to the Lesson 4 – Arrays and Lists on our tutorial series Learning C# with Zenva.

Tutorial Source Code

All of the source code for this tutorial can be downloaded here.

In this lesson, we will see what is an array and what is a list; the difference between them; how to declare and use them together with the for statement we learnt in the last lesson.

ARRAYS

An Array is a data collection of the same type. A feature of the arrays is that they are static, that is, the programmer cannot increase the amount of positions in runtime. So if we declare an array of int with 10 positions, these positions will remain until the end of the program for this array.

Arrays have the following syntax:

Data type[] arrayName;

Data Type: specify the type of elements in the array.

[ ] : specify the size of the array.

arrayName: specify the name of the array.

When we declare an array, it does not mean it is initialized in the memory because by now, we cannot assign values to it.

Arrays, lists and objects, need to be initialized so we can assign them values. To initialized these structs, we use the word new. For example:

int[] ages = new int[5]

Remember: An array start its index in position 0. It means, an array with 3 positions will have as index: [0][1][2]. We can have access to the array content using the index. There are several ways to assign value to an array. Let’s see them:

Using the index number:

string[] names = new string[5]
names[0] = "Zenva";

When we declare the array:

int[] numbers = new int[5] {10, 20, 30, 40, 50}

double[] salary = {150.0, 2400.0, 175.39, 788.68}

//In this case, the array salary has 4 positions.

We can also omit the size:

int[] score = new int[] {10, 20, 30, 40, 50}

//In this case, the array length is 5.

Note: ‘//’ is used to write comments in the code.

We can assign a value from an array, using the index, to a variable:

int[] numbers = new int[5] {10, 20, 30, 40, 50}

int n1 = numbers[3]; //Now n1 = 30.

Time to write some code! Let’s start a new Project and name it ArrayAndList. Write or copy and paste the code below.

Array example:

using System;

namespace ArrayAndList
{
    class Program
    {
        static void Main(string[] args)
        {
            //String array with 3 elements
            string[] names = new string[3];
            names[0] = "Davis";
            names[1] = "Matt";
            names[2] = "Bob";

            for(int i = 0; i < names.Length; i++)
            {
                Console.WriteLine("Position number "+ i +": "+ names[i]);
            }

            Console.Read();
        }
    }
}

In this example, we declared an array of type string with 3 positions and we wrote one name on each position. Then we showed that content of the array using a flow control we learnt last lesson, “for”, to go through each position of the array. Reading the command: “from i = 0 to names.length (in this case length = 3), do something, then, increment the variable i.”

Running our application:

image1

We can also use the structure for to fill our array with numbers, for instance:

int[] numbers = new int[3];

for (int i = 0; i < numbers.Length; i++)
{
   numbers[i] = i + 5;
   Console.WriteLine("Our array numbers has in position [" + i + "] the value: " + numbers[i]);
}

LISTS

A List(T) has the same characteristics of an array. However, a List(T) can be increased dynamically. In a List(T), we do not establish its length. As we need more values to be put into a list, we simply write the method ‘Add’ and we add a new value.

A List(T) has the following syntax:

List<data type> listName;

Also to initialize the list we use the word ‘new’.

listName = new List<data type>();

Both arrays and lists are very easy to work. Also, they are simple and powerful.

List example:

using System;
using System.Collections.Generic;

namespace ArrayAndList
{
    class Program
    {
        static void Main(string[] args)
        {
            #region

            //Declaring a list "int".
            List<int> list = new List<int>();

            //Populating the list with 10 elements
            for(int i = 0; i <= 10; i++)
            {
                list.Add(i*9);
            }

            int x = 0;

            //foreach element in the list do:
            foreach(int element in list)
            {
                Console.WriteLine("9 * " + x + " = " + element);
                x++;
            }

            Console.Read();
        }
    }
}

In this example, we did the multiplication table 9. It was declared a list of type int and we add some numbers using the repeat loop for. Then we showed its content by using the foreach. Also, we need to declare on the top of the code, the using System.Collections.Generic to be able to use List(T).

Running our application:

image2

We can also add items provided by an array in a list. With an array to check its size, we use the method length. With a List(T), we use the method Count.

List<double> orders = new List<double>(new double[] { 19.99, 6.48, 25.0 });

            for (int i = 0; i < orders.Count ; i++)
            {
                Console.WriteLine("Order number " + i + " : $ " + orders[i]);
            }

Count: We can assign the size of a list to a variable by writing:

int ordersQuantity = orders.Count;

Console.WriteLine(ordersQuantity);

//Result: 3

Clear: To remove all the elements from a list we use the function Clear().

orders.Clear();

Console.WriteLine(orders.Count);

//Result: 0

IndexOf: Give us the element index of a value in the List(T). When the method IndexOf does not find the value, it returns as value -1;

int index = orders.IndexOf(25.0);
Console.WriteLine(index);

//Result: 2

Reverse: Invert the order of the elements in the list.

List<string> cars = new List<string>(new string[] { "Ferrari", "Lamborghini", "Range Rover" });
cars.Reverse();

foreach (var car in cars)
{
    Console.WriteLine(car);
}

//Result:
//Range Rover
//Lamborghini
//Ferrari

Distinct: Remove duplicates elements in the list. This method belongs to System.Linq, so we need to add this using System.Linq in our application.

List<int> oldList = new List<int>(new int[] { 1, 2, 2, 3, 4, 4, 5 });

//Get distinct elements and convert into a list again.
List<int> newList = oldList.Distinct().ToList();

foreach (var item in newList)
{
    Console.WriteLine(item);
}

//Result
//1
//2
//3
//4
//5

This is the end of this tutorial. I hope you have enjoyed and I see you in the next lesson!

Thank you!