×

c# · level 2 · unit 1 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.