C#, lesson 7
One variable holds one value. For a shopping list, a week of temperatures or a phone book, you
need a collection. The three you will use most are arrays, lists and dictionaries. Lists and
dictionaries live in the System.Collections.Generic namespace, so add that using line.
An array has a fixed length and one element type. Indexes start at 0:
Reading scores[3] throws an IndexOutOfRangeException; the last valid index is
Length - 1. You have already met an array: Split returns a string[].
2 exercises to try what you just read.
The square-bracket syntax [12, 7, 30] is a collection expression. It works for arrays,
lists and many other collection types.
The <string> is a type argument: this list holds strings and nothing else. A List<int>
holds numbers. Notice that arrays use Length while lists use Count.
To visit every element in order, use foreach. It works for arrays and every collection:
You cannot add or remove items from a list while a foreach is walking through it; build a new
list instead, or use an index-based for loop.
A dictionary maps keys to values. Each key appears at most once:
Reading a key that is not there with stock["kiwi"] throws a KeyNotFoundException. The safe
way to look something up is TryGetValue, which returns true or false and gives you the
value through an out variable:
Loop over the pairs with foreach; each item has a Key and a Value:
The var (fruit, amount) part deconstructs each pair into two variables. Do not rely on the
order of a Dictionary; if you need keys sorted, use a SortedDictionary.
The input is one line of whole-number temperatures separated by spaces (at least one). Print the lowest, the highest, the average with one decimal place, and how many days were strictly warmer than the average.
Sample input:
Sample output:
The first line is a number N. The next N lines each hold a name and a phone number separated
by a space. Every line after that is a name to look up. For each lookup, print the number, or
Not found if the name is not in the book. Names are case sensitive. If a name appears twice in
the book, the later number wins.
Sample input:
Sample output:
int[] scores = [12, 7, 30]; // a collection expression
Console.WriteLine(scores[0]); // 12
scores[1] = 8; // replace an element
Console.WriteLine(scores.Length); // 3
Console.WriteLine(scores[^1]); // 30: ^1 means "first from the end"
double[] prices = new double[5]; // five zeros, filled in laterusing System.Collections.Generic;
List<string> cart = ["apples", "bread"];
cart.Add("cheese");
cart.Insert(0, "milk"); // at the front
cart.Remove("bread");
Console.WriteLine(cart.Count); // 3
Console.WriteLine(cart[1]); // apples
Console.WriteLine(cart.Contains("milk")); // True
Console.WriteLine(string.Join(", ", cart)); // milk, apples, cheeseint total = 0;
foreach (int s in scores)
{
total += s;
}Dictionary<string, int> stock = new();
stock["apple"] = 12; // add or replace
stock["pear"] = 4;
stock["apple"] = 10; // replaces 12
Console.WriteLine(stock["apple"]); // 10
Console.WriteLine(stock.ContainsKey("kiwi")); // False
Console.WriteLine(stock.Count); // 2if (stock.TryGetValue("kiwi", out int count))
{
Console.WriteLine($"{count} kiwis");
}
else
{
Console.WriteLine("No kiwis");
}foreach (var (fruit, amount) in stock)
{
Console.WriteLine($"{fruit}: {amount}");
}12 15 9 20 18 11 14Min: 9
Max: 20
Average: 14.1
Above average: 33
alice 555-1234
bob 555-9876
carol 555-2468
bob
dave
alice555-9876
Not found
555-1234