BeginnerLesson 6 of 16
Arrays, Lists, Dictionaries, Sets – C#
The most important collection types and how to use them.
Array (fixed length), List<T> (growing list), Dictionary<K,V> (key → value) and HashSet<T> (unique values). The index ^1 stands for the last element, and .. creates ranges.
int[] feld = { 10, 20, 30, 40 };
Console.WriteLine(feld[^1]); // 40
Console.WriteLine(string.Join(",", feld[1..3])); // 20,30
var zahlen = new List<int> { 3, 1, 2 };
zahlen.Add(5);
zahlen.Sort();
Console.WriteLine(string.Join(", ", zahlen)); // 1, 2, 3, 5
Console.WriteLine($"{zahlen[0]} {zahlen[^1]} {zahlen.Count}"); // 1 5 4You access dictionaries through the indexer; TryGetValue and GetValueOrDefault avoid exceptions for missing keys. Sets ignore duplicates.
var person = new Dictionary<string, string>
{
["name"] = "Ada",
["stadt"] = "London"
};
person["alter"] = "36";
foreach (var (schluessel, wert) in person)
Console.WriteLine($"{schluessel} = {wert}");
Console.WriteLine(person.GetValueOrDefault("email", "none"));
if (person.TryGetValue("name", out var n)) Console.WriteLine(n);
var menge = new HashSet<int> { 1, 2, 2, 3, 3 };
Console.WriteLine(menge.Count); // 3WarningDirect access
person["email"] to a missing key throws a KeyNotFoundException. Also, do not rely on any particular order when iterating over a dictionary.TipFor collections that callers should only read, return
IReadOnlyList<T> or IEnumerable<T> – that keeps the internal list protected.