c# · level 2 · unit 1 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Lists can change: swap, squeeze in, take out and .
fruit[1] = "pear" swaps the item at index 1 for a new one. squeezes an item in: .Insert(0, "kiwi") puts kiwi at the front, and every item after it shifts along one place to make room.
.Remove("plum") takes out the first item that matches, while takes out whatever sits at an index, like .RemoveAt(2). Either way, the items after the gap shift back, so their indexes drop by one. Ask for an index the list does not have and C# stops with ArgumentOutOfRangeException.
Sort puts the whole list in order: .Sort() lines numbers up smallest first and text from A to Z.
using System;
using System.Collections.Generic;
List<string> fruit = new List<string> { "plum", "apple", "banana" };
fruit[1] = "pear";
fruit.Insert(0, "kiwi");
fruit.Remove("plum");
fruit.Sort();
Console.WriteLine(string.Join(", ", fruit)); .Remove wants the item itself, .RemoveAt wants an index.
guess first
Someone leaves, someone joins. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
using System.Collections.Generic;
List<string> queue = new List<string> { "Ada", "Ben", "Cara" };
queue.RemoveAt(0);
queue.Insert(1, "Dev");
Console.WriteLine($"{string.Join(", ", queue)} ({queue.Count})");
your turn
Your turn. Throw away the worst score.
Add a score of your own on line 5. The list is sorted on line 6, so on line 7 remove the lowest score by its index. Press run to see the scores you kept.
output
press run to see what happens
fix it
The first job will not go away. Fix it!
output
press run to see what happens
- C# says
CS1503on line 5: it cannot turn0into a string. What does.Removelook for? .Removewants the item itself. To take out an item by its index, use the other method.- Change
jobs.Remove(0)tojobs.RemoveAt(0)on line 5, then press run.
nailed it
you can change a list any way you like. :D
list[i] = valueswaps,.Insertsqueezes in..Removetakes an item,.RemoveAttakes an index..Sort()puts the whole list in order.
new words in your collection
- Insert
- RemoveAt
- Sort
This lesson isn’t saved. A free account remembers every lesson you finish.