CodeBlanks Logo Icon CodeBlanks

Summary - Generic collections

C# course · Intermediate · Lesson 81/116

Combine List, Dictionary and Queue to write a task queue.

Summary - Generic collections

In this group you studied five generic collections in depth. List<T> is a dynamic array, Dictionary<K,V> a hash table, SortedDictionary<K,V> a sorted tree, Queue<T> a FIFO sequence, LinkedList<T> a doubly linked list.

Each collection serves a different strength: fast lookup, ordered iteration, end insertion, or memory efficiency. Now two small tasks let you combine them.

Exercise AddRange to a list, print Count

Use AddRange to add 4, 5, 6 to list below. Then print list.Count with Console.WriteLine.

Show example solution
Add three items with AddRange, then print Count.
Example solution:
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var list = new List<int> { 1, 2, 3 };
        list.AddRange(new[] { 4, 5, 6 });
        Console.WriteLine(list.Count);
    }
}

Exercise Check a key with ContainsKey

Use ContainsKey to check whether "apple" is in the prices dictionary below; print the result with Console.WriteLine.

Show example solution
ContainsKey returns a bool; print it with WriteLine.
Example solution:
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        var prices = new Dictionary<string, int>();
        prices.Add("apple", 5);
        prices.Add("pear", 3);
        Console.WriteLine(prices.ContainsKey("apple"));
    }
}

Choosing a collection

Choosing the right collection drives performance. For fast lookup pick Dictionary<K,V>, for ordered iteration SortedDictionary<K,V>, for a FIFO sequence Queue<T>, for fast end insertion LinkedList<T>.

The next group covers the iteration interfaces and the yield keyword, so you can write your own collection.

Test yourself

  1. Unique and sorted keys?

    • List<T>
    • SortedDictionary<K,V>
    • Queue<T>
    • LinkedList<T>
    Show answer

    SortedDictionary<K,V> — Correct. SortedDictionary keeps unique keys in order.

  2. Complete the sorted dictionary

    var ordered = new Sorted____<string, int>();
    Show answer
    var ordered = new SortedDictionary<string, int>();

All lessons in Intermediate