Learn to keep many values under one name: fixed-size arrays, the flexible List<T>, and a sensor data average example.
Array: numbered boxes in a row
Keeping the temperatures from 5 sensors in separate variables like s1, s2, s3... is hard. An array stores many values of the same type side by side, with numbers. The numbers are called indexes and they start at 0.
double[] temperatures = { 21.5, 22.1, 20.9, 23.4, 22.8 };
Console.WriteLine(temperatures[0]); // first element: 21.5
Console.WriteLine(temperatures[4]); // last element: 22.8
Console.WriteLine(temperatures.Length); // number of elements: 5
temperatures[2] = 21.0; // change an element
To create an empty array, you give its size: int[] numbers = new int[10]; (all start as 0). The size of an array does not change later.
Out of range: If you write array[5] on an array with 5 elements, you get an IndexOutOfRangeException; the valid indexes are 0-4. The "off-by-one" error is one of the most common mistakes of beginners.
Working on an array: the average
double[] measurements = { 21.5, 22.1, 20.9, 23.4, 22.8 };
double total = 0;
double largest = measurements[0];
double smallest = measurements[0];
foreach (double value in measurements)
{
total += value;
if (value > largest) largest = value;
if (value < smallest) smallest = value;
}
double average = total / measurements.Length;
Console.WriteLine($"Average: {average:F2} °C");
Console.WriteLine($"Lowest: {smallest}, highest: {largest}");
Average: 22.14 °C
Lowest: 20.9, highest: 23.4
The total is 110.7; divided by five values it comes to 22.14. This is the core of a real measurement program.
Walking with an index using for
If you want to know the index, use for:
string[] channels = { "CH1", "CH2", "CH3" };
for (int i = 0; i < channels.Length; i++)
{
Console.WriteLine($"{i}: {channels[i]}");
}
Helpers of the Array class
int[] numbers = { 42, 7, 19, 3 };
Array.Sort(numbers); // smallest to largest
Console.WriteLine(string.Join(", ", numbers));
Array.Reverse(numbers); // reverse it
Console.WriteLine(string.Join(", ", numbers));
Console.WriteLine(Array.IndexOf(numbers, 19)); // index of 19
3, 7, 19, 42
42, 19, 7, 3
1
List<T>: a list that grows and shrinks
The size of an array is fixed. When you don't know how many elements will come (for example, new measurements will be added as a sensor keeps running), you use List<T>. Here T is the type parameter: List<int> is a list of integers, and List<string> is a list of text.
var measurements = new List<double>();
measurements.Add(3.3);
measurements.Add(3.1);
measurements.Add(3.4);
measurements.Insert(0, 3.0); // add at the beginning
Console.WriteLine(measurements.Count); // 4
measurements.Remove(3.1); // remove by value
measurements.RemoveAt(0); // remove by index
Console.WriteLine(measurements.Contains(3.4)); // True
foreach (var d in measurements) Console.WriteLine(d);
4
True
3.3
3.4
The number of elements is called Length in an array and Count in a list; mixing the two up is a common mistake.
Sorting and searching
var scores = new List<int> { 70, 45, 90, 62 };
scores.Sort();
Console.WriteLine(string.Join(" ", scores)); // 45 62 70 90
int firstPassing = scores.Find(n => n >= 60); // first element that satisfies the condition
Console.WriteLine(firstPassing); // 62
n => n >= 60 is a lambda expression: a small, nameless method that means "given n, tell me whether n is greater than or equal to 60". We will use lambdas heavily in the LINQ lesson.
Which one should I pick? If the size is known from the start and will not change, use an array; if you will add and remove items, use List<T>. In new code, List<T> is used most of the time.
Try it yourself
Create a List<double> and keep asking the user for voltage measurements until they type "done" (with while and TryParse). At the end, print how many measurements were taken, the average and the largest value. Add a check so that you don't get a division error if no measurement was entered.
// Mini quiz
Click an option; you will see right away, with the reason, whether it is correct or not.
Mark it when you finish: your progress is saved and you earn +20 XP.
Tip: ← → keys let you move between lessons.