List Collection

Create lists

// list
var names = new List<string> { "<name>", "Ana", "Felipe" };
foreach (var name in names)
{
    Console.WriteLine($"Hello {name.ToUpper()}!");
}

Modify list contents

// list operations
var names = new List<string> { "<name>", "Ana", "Felipe" };
Console.WriteLine();
names.Add("Maria");
names.Add("Bill");
names.Remove("Ana");
foreach (var name in names)
{
    Console.WriteLine($"Hello {name.ToUpper()}!");
}

// list index
Console.WriteLine($"My name is {names[0]}.");
Console.WriteLine($"I've added {names[2]} and {names[3]} to the list.");

// count: len(list)
Console.WriteLine($"The list has {names.Count} people in it");

Search and sort lists

// Search
var names = new List<string> { "<name>", "Ana", "Felipe" };
var index = names.IndexOf("Felipe");
if (index != -1)
{
    Console.WriteLine($"The name {names[index]} is at index {index}");
    // The name Felipe is at index 2
}

var notFound = names.IndexOf("Not Found");
Console.WriteLine($"When an item is not found, IndexOf returns {notFound}");
// When an item is not found, IndexOf returns -1

// Sort
names.Sort();
foreach (var name in names)
{
    Console.WriteLine($"Hello {name.ToUpper()}!");
}

Lists of other types

// Fibonacci sequence
var fibonacciNumbers = new List<int> {1, 1};
var previous = fibonacciNumbers[fibonacciNumbers.Count - 1];
var previous2 = fibonacciNumbers[fibonacciNumbers.Count - 2];

fibonacciNumbers.Add(previous + previous2);

foreach(var item in fibonacciNumbers)
    Console.WriteLine(item);

Challenge: print first 20 Fibonacci numbers

// More Fibonacci sequence
var fibonacciNumbers = new List<int> {1, 1};
var previous = fibonacciNumbers[fibonacciNumbers.Count - 1];
var previous2 = fibonacciNumbers[fibonacciNumbers.Count - 2];

while (fibonacciNumbers.Count < 20)
{
    fibonacciNumbers.Add(previous + previous2);
    previous = fibonacciNumbers[fibonacciNumbers.Count - 1];
    previous2 = fibonacciNumbers[fibonacciNumbers.Count - 2];
}

foreach(var item in fibonacciNumbers)
    Console.WriteLine(item);

Last updated