C# Programming · Lesson 6

Lining Up Your Ducks with Collections — Programming Examples

Five runnable C# examples covering arrays, foreach, sorting, var arrays, List<T>, dictionaries, collection initializers, and HashSet set operations.

  • arrays
  • foreach
  • sorting
  • lists
  • dictionaries
  • initializers
  • hashsets
  • collections

Example 1 — Average Quiz Scores with an Array and foreach

A fixed-size array holds five quiz scores set with an initializer, and a foreach loop adds them up without an index. A second array is sized at runtime from the user’s input, which shows that both kinds of arrays use the same Length property.

using System;

class Program
{
    static void Main()
    {
        int[] quizScores = { 88, 92, 75, 100, 81 };
        int total = 0;

        foreach (int score in quizScores)
        {
            total += score;
        }

        double average = (double)total / quizScores.Length;
        Console.WriteLine("Quizzes: " + quizScores.Length);
        Console.WriteLine("Average: " + average.ToString("F1"));

        Console.Write("How many labs were assigned? ");
        int labCount = int.Parse(Console.ReadLine() ?? "0");
        int[] labScores = new int[labCount];

        for (int i = 0; i < labScores.Length; i++)
        {
            Console.Write("Score for lab " + (i + 1) + ": ");
            labScores[i] = int.Parse(Console.ReadLine() ?? "0");
        }

        Console.WriteLine("Labs recorded: " + labScores.Length);
    }
}

Example 2 — Rank Students with Array.Sort and a Bubble Sort

Array.Sort puts the names in alphabetical order in place; it returns nothing. The hand-written bubble sort then compares neighbors and swaps them, so the highest exam score rises to the front. The var arrays are still strongly typed string[] and int[].

using System;

class Program
{
    static void Main()
    {
        var names = new[] { "Morgan", "Avery", "Jordan", "Casey" };
        var scores = new[] { 78, 95, 84, 91 };

        Array.Sort(names);
        Console.Write("Alphabetical:");
        foreach (string name in names)
        {
            Console.Write(" " + name);
        }
        Console.WriteLine();

        for (int pass = 0; pass < scores.Length - 1; pass++)
        {
            for (int i = 0; i < scores.Length - 1 - pass; i++)
            {
                if (scores[i] < scores[i + 1])
                {
                    int temp = scores[i];
                    scores[i] = scores[i + 1];
                    scores[i + 1] = temp;
                }
            }
        }

        Console.Write("Highest to lowest:");
        foreach (int score in scores)
        {
            Console.Write(" " + score);
        }
        Console.WriteLine();
    }
}

Example 3 — Manage a Class Waitlist with List<T>

A List<string> grows and shrinks as students join and leave, which an array can’t do. The program uses Add, Insert, Contains, IndexOf, RemoveAt, and Count, then copies the list to an array with ToArray.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> waitlist = new List<string>();
        waitlist.Add("Riley");
        waitlist.Add("Sam");
        waitlist.AddRange(new[] { "Taylor", "Jamie" });
        waitlist.Insert(0, "Drew");

        Console.WriteLine("Students waiting: " + waitlist.Count);

        if (waitlist.Contains("Sam"))
        {
            int position = waitlist.IndexOf("Sam");
            Console.WriteLine("Sam is at position " + (position + 1));
            waitlist.RemoveAt(position);
            Console.WriteLine("Sam enrolled and left the waitlist.");
        }

        int missing = waitlist.IndexOf("Quinn");
        Console.WriteLine("IndexOf Quinn: " + missing);

        string[] snapshot = waitlist.ToArray();
        waitlist.Add("Quinn");

        Console.WriteLine("Snapshot size: " + snapshot.Length);
        Console.WriteLine("Current size: " + waitlist.Count);

        foreach (string student in waitlist)
        {
            Console.WriteLine("- " + student);
        }
    }
}

Example 4 — Look Up Credit Hours with a Dictionary

A Dictionary<string, int> maps each course code to its credit hours, and a collection initializer makes the starting data easy to read. ContainsKey checks for a code before the program looks it up with square brackets, so a missing code doesn’t throw an exception, and foreach walks each KeyValuePair.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        Dictionary<string, int> credits = new Dictionary<string, int>
        {
            { "IST 2373", 3 },
            { "IST 1133", 3 },
            { "MAT 1313", 3 },
            { "BIO 1134", 4 }
        };

        credits.Add("SPT 1113", 3);

        Console.Write("Course code: ");
        string code = Console.ReadLine() ?? "";

        if (credits.ContainsKey(code))
        {
            Console.WriteLine(code + " is worth " + credits[code] + " credit hours.");
        }
        else
        {
            Console.WriteLine(code + " is not in the catalog.");
        }

        if (credits.ContainsValue(4))
        {
            Console.WriteLine("At least one course is worth 4 credit hours.");
        }

        int totalHours = 0;
        foreach (KeyValuePair<string, int> course in credits)
        {
            Console.WriteLine(course.Key + ": " + course.Value);
            totalHours += course.Value;
        }

        Console.WriteLine("Courses: " + credits.Count + ", Total hours: " + totalHours);
    }
}

Example 5 — Compare Club Rosters with HashSet Operations

A HashSet<string> keeps only unique names, so Add returns false for a duplicate. UnionWith, IntersectWith, and ExceptWith change the set they are called on, so each one works on a copy and the original rosters stay intact.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        HashSet<string> codingClub = new HashSet<string> { "Ava", "Ben", "Cole", "Dana" };
        HashSet<string> roboticsClub = new HashSet<string> { "Cole", "Dana", "Eli" };

        bool added = codingClub.Add("Ben");
        Console.WriteLine("Added Ben again? " + added);

        HashSet<string> allMembers = new HashSet<string>(codingClub);
        allMembers.UnionWith(roboticsClub);

        HashSet<string> inBoth = new HashSet<string>(codingClub);
        inBoth.IntersectWith(roboticsClub);

        HashSet<string> codingOnly = new HashSet<string>(codingClub);
        codingOnly.ExceptWith(roboticsClub);

        Console.Write("All members:");
        foreach (string name in allMembers)
        {
            Console.Write(" " + name);
        }
        Console.WriteLine();

        Console.Write("In both clubs:");
        foreach (string name in inBoth)
        {
            Console.Write(" " + name);
        }
        Console.WriteLine();

        Console.Write("Coding only:");
        foreach (string name in codingOnly)
        {
            Console.Write(" " + name);
        }
        Console.WriteLine();

        Console.WriteLine("Coding club still has " + codingClub.Count + " members.");
    }
}