Learn C# · lesson 28 of 61 · about 8 minutes
Looping and Searching
Sort the bag, count and sell the gems with foreach, and look for the gate key with Contains.
What you'll learn
- Loop over a list with foreach and for
- Search with Contains and IndexOf
- Track a maximum or a count
Sorting the bag
Before the last gate, the hero tidies the bag: bag.Sort() puts the items in alphabetical order. A trader buys every gem for 15 gold, and a foreach loop counts how many there are. The gate needs a key, and bag.Contains("key") says whether there is one.
Finding things
list.Contains(x): is it there?list.IndexOf(x): where, or -1list.Sort(): puts the items in order, low to high- For anything else, loop and keep track: a count, a total, or the best so far
Don't Add or Remove items while a foreach is visiting the same list; C# throws an exception. Use a for loop or build a new list instead.
Searching
List<int> temps = new() { 12, 18, 9, 21, 15 };
Console.WriteLine($"{temps.Contains(21)} {temps.IndexOf(9)} {temps.IndexOf(30)}");
int warmDays = 0, hottest = temps[0];
foreach (int t in temps)
{
if (t >= 15) warmDays++;
if (t > hottest) hottest = t;
}
Console.WriteLine($"{warmDays} warm days, hottest {hottest}");
temps.Sort();
Console.WriteLine(string.Join(" ", temps));Output
True 2 -1
3 warm days, hottest 21
9 12 15 18 21Tip
Start a best-so-far at the first item, not at 0. If every item were negative, a start of 0 would win without being in the list at all.
Now try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.