C# Tutorial menu

C# Arrays and Lists

Arrays and lists let you keep many values of the same type together under one name.

Arrays

An array has a fixed size. Create it with values in curly braces:

Example

csharp
string[] students = { "Ali", "Ayesha", "Bilal" };
int[] marks = { 81, 94, 67 };

Console.WriteLine(students[0]);
Console.WriteLine(marks[2]);

marks[2] = 72;
Console.WriteLine(marks[2]);
Console.WriteLine($"Count: {marks.Length}");
Output
Ali
67
72
Count: 3

You can also create an empty array of a set size. Every number starts at 0:

Example

csharp
int[] scores = new int[5];

Using an index outside the array, like marks[3] in an array of 3 items, throws an IndexOutOfRangeException. Valid indexes are 0 to Length - 1.

Looping and Sorting Arrays

Example

csharp
int[] prices = { 750, 120, 990, 300 };
Array.Sort(prices);

foreach (int p in prices)
{
    Console.Write(p + " ");
}
Console.WriteLine();
Console.WriteLine($"Cheapest: {prices[0]}");
Output
120 300 750 990 
Cheapest: 120

Lists

A List<T> is like an array that can grow and shrink. The T is the type of items, for example List<string>:

Example

csharp
List<string> cart = new List<string> { "Sugar", "Tea" };

cart.Add("Milk");
cart.Add("Biscuits");
cart.Remove("Tea");

Console.WriteLine($"Items: {cart.Count}");
foreach (string item in cart)
{
    Console.WriteLine("- " + item);
}
Console.WriteLine(cart.Contains("Milk"));
Output
Items: 3
- Sugar
- Milk
- Biscuits
True

List lives in the System.Collections.Generic namespace. New console projects include it automatically; in older projects add using System.Collections.Generic; at the top.

Common List Methods

MemberWhat it does
list.Add(x)Adds an item at the end
list.Insert(i, x)Adds an item at position i
list.Remove(x)Removes the first matching item
list.RemoveAt(i)Removes the item at position i
list.CountNumber of items
list.Contains(x)True if the item is in the list
list.Sort()Sorts the list
list.Clear()Removes everything

Array or List?

ArrayList
SizeFixedGrows and shrinks
Number of itemsLengthCount
Best forData that never changes sizeMost everyday code

Quick Calculations

The System.Linq methods give quick answers about arrays and lists:

Example

csharp
List<int> results = new List<int> { 55, 78, 91, 64 };

Console.WriteLine(results.Max());
Console.WriteLine(results.Min());
Console.WriteLine(results.Sum());
Console.WriteLine(results.Average());
Output
91
55
288
72

Exercise

Exercise

Which property gives the number of items in a List?

Learn C# with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp