Learning CSharp basics part-3 Array, List, foreach loop


list and array in CSharp

Array and List are used to store multiple values in a single variable. The values stored in an array are generally related in contrast to list which can hold values with different data types. Both array and list use a zero-based numeric index to access their elements.


Differences between Array and List

Array and list are two different data structure in C#.

  1. Array is fixed-sized meaning, you can’t add or remove elements after instantiation.
  2. List is dynamic size and it can grow or shrink in size by adding or removing elements.
  3. Array’s elements are of the same data type
  4. List is a generic collection, meaning it can hold elements of any type.
  5. Array is more performant

Array

Create/Instantiate an array: To instantiate an array you can use “new” keyword + data type + size/quantity. And it is not possible to add more items to the array than it’s defined size/quantity.

// data_type[] array_name = new data_type[size];
string[] cars = new string[3];

Assign values to array:

cars[0] = "Toyota";
cars[1] = "Nissan";
cars[2] = "Kia";

Console.WriteLine($"Third Car is: {cars[2]}");

Initialize an array:

string[] cars = {"Toyota", "Nissan", "Kia"};

Console.WriteLine($"Third Car is: {cars[2]}");

Length of array:

Console.WriteLine($"There are {cars.Length} brands of cars in parking.");


List

Create/Instantiate a List:

List<string> cars = new List<string>();

Adding values to list using Add():

cars.Add("Toyota");
cars.Add("Nissan");
cars.Add("Kia");
cars.Add("Hyundai");

Removing values from list using Remove():

cars.Remove("Toyota");

Length of list:

Console.WriteLine($"There are {cars.Count} brands of cars in parking.");

Both array and list are zero-based indexed so you can access their elements or loop through them the same.

Reassign the value of an array or list:

cars[2] = "Hyundai";

Console.WriteLine($"Third Car is: {cars[2]}");
// output: Third Car is: Hyundai

foreach loop

foreach loop has the same syntax as any other foreach loop in C family languages.

Loop through array or list with foreach:

// array
// int[] tempraturs = {22, 26, 25, 40};

// list
List<int> tempraturs = new List<int> {22, 26, 25, 40};

int sum_temp = 0;

// foreach loop is the same for both array and list
foreach (int temp in tempraturs)
{
    sum_temp += temp;
}

// For arrays you can use array.Length
decimal average_temp = (decimal)sum_temp / tempraturs.Length;

// For lists you can use List.Count
decimal average_temp2 = (decimal)sum_temp / tempraturs.Count;

Console.WriteLine(average_temp);
/* 
output:
28.25
*/



Tags: