Important People in C

  • Anders Hejlsberg
  • Mas Torgessen
  • Stephen Toub

CSharp Generic Collections

// Namespaces required for collections:
 using System.Collections
 using System.Collections.Generic

Don't confuse System.Collections.Generic with the older System.Collections namespace which existed before generics were added to C#.

Microsoft recommends using Generics as they are faster and more type safe.

Some standard C# Collections

  • ArrayList
  • Generic List
  • Dictionary List

Examples will be based on the following Student class, for generating a list of students to work with as a collection of Student objects.

using System;
namespace CollectionsTest
{
    public class Student
    {
        public int Id { get; set; }
        public string Firstname { get; set; }
        public string Surname { get; set; }
        public int Age { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="T:CollectionsTest.Student"/> class.
        /// Simplistic representation of a student
        /// </summary>
        /// <param name="id">Identifier.</param>
        /// <param name="firstname">Firstname.</param>
        /// <param name="surname">Surname.</param>
        /// <param name="age">Age.</param>
        public Student(int id = 0, string firstname = "", string surname = "", int age = 0)
        {
            Firstname = firstname;
            Surname = surname;
            Age = age;
            Id = id;
        }

        public override string ToString()
        {
            return $"{Id} {Firstname} {Surname}, {Age}";
        }
    }
}

ArrayLists in CSharp

Example of working with array lists, showing three different syntax forms.

using System;
using System.Collections;
using System.Collections.Generic;

namespace CollectionsTest
{
    /// <summary>
    ///  Program to demonstrate use of ArrayLists  in C#
    ///  Relies on a Student classes to generate and work on a list of students.
    /// </summary>
    class MainClass
    {
        public static void Main()
        {
            int id = 0;
            Student joe = new Student() { Id = id++, Firstname = "Joe", Surname = "Mangwana", Age = 20 };
            Student sue = new Student() { Id = id++, Firstname = "Sue", Surname = "Morena", Age = 22 };
            Student pat = new Student() { Id = id++, Firstname = "Pat", Surname = "Manhinga", Age = 25 };
            Student rat = new Student() { Id = id++, Firstname = "Rat", Surname = "Mopedzi", Age = 30 };

            // C# ArrayLists
            // ArrayLists are not strongly typed. Just take note of that
            ArrayList studentList = new ArrayList();
            studentList.Add(joe);, Lists and Dictionary Lists
            studentList.Add(sue);
            studentList.Add(pat);
            studentList.Add(rat);

            // Simplified syntax - does same as above
            ArrayList studentListSimple = new ArrayList
            {
                joe,
                sue,
                pat,
                rat
            };

            // Alternative syntax - creating new students in place
            // keynames are required to reference the items, student.Firstname, etc
            id = 10;
            ArrayList studentArrayList = new ArrayList() {
                new Student() { Id = id++, Firstname = "Joe", Surname = "Mangwana", Age = 20 },
                new Student() { Id = id++, Firstname = "Sue", Surname = "Morena",   Age = 22 },
                new Student() { Id = id++, Firstname = "Pat", Surname = "Manhinga", Age = 25 },
                new Student() { Id = id++, Firstname = "Rat", Surname = "Mopedzi",  Age = 30 }
            };

            Console.WriteLine("\n --- Printing an ArrayList ---");
            foreach (Student student in studentArrayList)
            {
                Console.WriteLine(student);
            }
        }
    }
}

Generic Lists in CSharp

Generic list List``<T>{=html} are strongly typed. They can only be of one data type

Example showing three syntax forms of working with generic lists.

using System;
using System.Collections;
using System.Collections.Generic;

namespace CollectionsTest
{
    /// <summary>
    ///  Program to demonstrate use of ArrayLists  in C#
    ///  Relies on a Student classes to generate and work on a list of students.
    /// </summary>
    class MainClass
    {
        public static void Main()
        {
            int id = 0;
            Student joe = new Student() { Id = id++, Firstname = "Joe", Surname = "Mangwana", Age = 20 };
            Student sue = new Student() { Id = id++, Firstname = "Sue", Surname = "Morena", Age = 22 };
            Student pat = new Student() { Id = id++, Firstname = "Pat", Surname = "Manhinga", Age = 25 };
            Student rat = new Student() { Id = id++, Firstname = "Rat", Surname = "Mopedzi", Age = 30 };

            // Generic list.  List<T>
            // Generic list. long syntax form
            List<Student> learnerList = new List<Student>();
            learnerList.Add(joe);
            learnerList.Add(sue);
            learnerList.Add(pat);
            learnerList.Add(rat);

            // List<T> are strongly typed. Simplified syntax
            List<Student> learnerListSimple = new List<Student>
            {
                joe,
                sue,
                pat,
                rat
            };

            id = 10;
            List<Student> learnerListLong = new List<Student>
            {
                new Student() { Id = id++, Firstname = "Bri", Surname = "Dudzai",  Age = 20 },
                new Student() { Id = id++, Firstname = "Day", Surname = "Ringai",  Age = 22 },
                new Student() { Id = id++, Firstname = "Lot", Surname = "Molena",  Age = 25 },
                new Student() { Id = id++, Firstname = "Mas", Surname = "Sarudzo", Age = 30 }
            };

            Console.WriteLine("\n --- Printing from a Generic List ---");
            foreach (Student student in learnerListLong)
            {
                Console.WriteLine(student);
            }

            // Output
            //  --- Printing from a Generic List ---
            // 10 Bri Dudzai, 20
            // 11 Day Ringai, 22
            // 12 Lot Molena, 25
            // 13 Mas Sarudzo, 30

        }
    }
}

Dictionary Lists in CSharp

Dictionary Lists are a type of collection that uses key value pairs. Other languages refer to dictionaries as maps or associative arrays.

Keys in a Dictionary List must be unique.

Keyword: Dictionary<Tkey, TValue>

Example showing different syntaxes working with Dictionaries.

using System;
using System.Collections;
using System.Collections.Generic;

namespace CollectionsTest
{
    /// <summary>
    ///  Program to demonstrate use of Dictionary Lists  in C#
    ///  Relies on a Student classes to generate and work on a list of students.
    /// </summary>
    class MainClass
    {
        public static void Main()
        {

            int id = 0;
            Student joe = new Student() { Id = id++, Firstname = "Joe", Surname = "Mangwana", Age = 20 };
            Student sue = new Student() { Id = id++, Firstname = "Sue", Surname = "Morena", Age = 22 };
            Student pat = new Student() { Id = id++, Firstname = "Pat", Surname = "Manhinga", Age = 25 };
            Student rat = new Student() { Id = id++, Firstname = "Rat", Surname = "Mopedzi", Age = 30 };

            Dictionary<int, Student> studentDictionary = new Dictionary<int, Student>();
            studentDictionary.Add(joe.Id, joe);
            studentDictionary.Add(sue.Id, sue);
            studentDictionary.Add(pat.Id, pat);
            studentDictionary.Add(rat.Id, rat);

            // Dictionary list - short syntax of the above
            Dictionary<int, Student> studentDictionarySimple = new Dictionary<int, Student>
            {
                { joe.Id, joe },
                { sue.Id, sue },
                { pat.Id, pat },
                { rat.Id, rat }
            };

            // Alternative syntax to initialise dictionaries
            id = 2;
            Dictionary<int, Student> studentDictionaryLong = new Dictionary<int, Student>()
            {
                [id++] = new Student() { Id = id, Firstname = "Bri", Surname = "Dudzai", Age = 20 },
                [id++] = new Student() { Id = id, Firstname = "Day", Surname = "Ringai", Age = 22 },
                [id++] = new Student() { Id = id, Firstname = "Lot", Surname = "Molena", Age = 25 },
                [id++] = new Student() { Id = id, Firstname = "Mas", Surname = "Sarudzo", Age = 30 }
            };

            Console.WriteLine("\n --- Print Dictionary List by keys --- ");
            foreach (var key in studentDictionaryLong.Keys)
            {
                Student student = new Student();
                student = studentDictionaryLong[key];
                Console.WriteLine(student);
            }

            Console.WriteLine("\n --- Printing Dictionary List using TryGetValue --- ");
            foreach (var key in studentDictionaryLong.Keys)
            {
                Student student = new Student();
                if (studentDictionaryLong.TryGetValue(key, out student))
                    Console.WriteLine(student);
            }

            Console.WriteLine("\n --- Printing Dictionary List using Key.Value pairs --- ");
            foreach (var pair in studentDictionaryLong)
            {
                // pair.Key, pair.Value to get a key or value
                Student student = new Student();
                student = pair.Value;
                Console.WriteLine(student);
            }

            Console.WriteLine("\n --- Iterate and print Dictionary values --- ");
            foreach (var studentValue in studentDictionaryLong.Values)
            {
                Student student = new Student();
                student = studentValue;
                Console.WriteLine(student);
            }

            // Output
            //
            //  --- Print Dictionary List by keys ---
            // 3 Joe Mangwana, 20
            // 4 Sue Morena, 22
            // 5 Pat Manhinga, 25
            // 6 Rat Mopedzi, 30
            //
            //  --- Printing Dictionary List using TryGetValue ---
            // 3 Joe Mangwana, 20
            // 4 Sue Morena, 22
            // 5 Pat Manhinga, 25
            // 6 Rat Mopedzi, 30
            //
            //  --- Printing Dictionary List using Key.Value pairs ---
            // 3 Joe Mangwana, 20
            // 4 Sue Morena, 22
            // 5 Pat Manhinga, 25
            // 6 Rat Mopedzi, 30
            //
            //  --- Iterate and print Dictionary values ---
            // 3 Joe Mangwana, 20
            // 4 Sue Morena, 22
            // 5 Pat Manhinga, 25
            // 6 Rat Mopedzi, 30
            //

        }
    }
}