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
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}");Ali 67 72 Count: 3
You can also create an empty array of a set size. Every number starts at 0:
Example
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
int[] prices = { 750, 120, 990, 300 };
Array.Sort(prices);
foreach (int p in prices)
{
Console.Write(p + " ");
}
Console.WriteLine();
Console.WriteLine($"Cheapest: {prices[0]}");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
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"));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
| Member | What 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.Count | Number 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?
| Array | List | |
|---|---|---|
| Size | Fixed | Grows and shrinks |
| Number of items | Length | Count |
| Best for | Data that never changes size | Most everyday code |
Quick Calculations
The System.Linq methods give quick answers about arrays and lists:
Example
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());91 55 288 72
Exercise
Exercise
Which property gives the number of items in a List?
