C# Collections

Collections

Each type of collection has its unique characteristics and is suitable for specific scenarios. Here’s a brief overview of the most common types of collections and when to use them:

Commonly used collections

1. List

  • Characteristics: An ordered collection of elements supports indexing.
  • Use When: You need to maintain the order of elements, and you require frequent access by index. It is similar to an array but can dynamically resize.
  • Example: Managing a list of students in a class.

2. HashSet

  • Characteristics: Unordered collection of unique elements without index.
  • Use When: You need to ensure that all elements are unique, and the order of elements doesn’t matter.
  • Example: Keeping track of unique visitors to a website.
3. Dictionary
  • Characteristics: Collection of key-value pairs, supports fast lookups by key.
  • Use When: You need to associate values with keys and perform fast lookups, additions, and deletions based on keys.
  • Example: Storing user profiles where the username is the key and the profile details are the value.
Examples to Illustrate Different Uses:
List Example:

List<string> students = new List<string>();
students.Add(“Alice”);
students.Add(“Bob”);
Console.WriteLine(students[0]); // Output: Alice

HashSet Example:

HashSet<int> uniqueNumbers = new HashSet<int>();
uniqueNumbers.Add(2);
uniqueNumbers.Add(1);
uniqueNumbers.Add(2); // Duplicate, will not be added
Console.WriteLine(uniqueNumbers.Count); // Output: 2

Dictionary Example:

// Example of a dictionary, a key-value pair collection
Dictionary<string, int> ageMap = new Dictionary<string, int>();
ageMap[“Alice”] = 25;
ageMap[“Bob”] = 30;

In a project scenario, let’s consider building a simple To-Do List application. This application will allow users to add tasks, remove tasks, and display the current list of tasks. This is a common requirement for productivity tools and can be easily managed using a List<T>.

Example: To-Do List Application

In this example, we’ll create a console application where users can manage their to-do list.

using System;
using System.Collections.Generic;
class Program
{
    public static void Main()
    {
        // Creating a list to store to-do tasks
        List<string> toDoList = new List<string>();
        while (true)
        {
            Console.WriteLine(“\nTo-Do List Application”);
            Console.WriteLine(“1. Add Task”);
            Console.WriteLine(“2. Remove Task”);           
            Console.WriteLine(“3. Display Tasks”);
            Console.WriteLine(“4. Exit”);
            Console.Write(“Choose an option: “);
            int option = int.Parse(Console.ReadLine());
            switch (option)
            {
                case 1:

                    Console.Write(“Enter a task to add: “);
                    string taskToAdd = Console.ReadLine();
                    toDoList.Add(taskToAdd);
                    Console.WriteLine(“Task added.”);
                    break;
                case 2:
                    Console.Write(“Enter the task to remove: “);
                    string taskToRemove = Console.ReadLine();
                    if (toDoList.Remove(taskToRemove))
                    {
                        Console.WriteLine(“Task removed.”);
                    }
                    else
                    {
                        Console.WriteLine(“Task not found.”);
                    }
                    break;
                case 3:
                    Console.WriteLine(“Current Tasks:”);
                    if(toDoList.Count == 0)
                    {
                        Console.WriteLine(“No tasks in the list.”);
                    }
                    else
                    {
                        foreach (string task in toDoList)
                        {
                            Console.WriteLine(“- ” + task);
                        }
                    }
                    break;
                case 4:
                    Console.WriteLine(“Exiting application.”);
                    return;
                default:
                    Console.WriteLine(“Invalid option. Please try again.”);
                    break;
            }
        }
    }
}

In a project scenario, let’s consider building a simple system to track unique visitors to a website. This application will allow us to add visitor IDs and ensure each ID is unique. This is a common requirement for web analytics and can be efficiently managed using a HashSet<T>.

Example: Unique Visitor Tracker

In this example, we’ll create a console application where visitor IDs are managed. We’ll be able to add visitor IDs and display the current set of unique visitor IDs.

using System;
using System.Collections.Generic;
class Program
{
    public static void Main()
    {
        // Creating a HashSet to store unique visitor IDs
        HashSet<string> visitorIDs = new HashSet<string>();
        while (true)
        {
            Console.WriteLine(“\nUnique Visitor Tracker”);
            Console.WriteLine(“1. Add Visitor ID”);
            Console.WriteLine(“2. Display Unique Visitor IDs”);
            Console.WriteLine(“3. Exit”);
            Console.Write(“Choose an option: “);
            int option = int.Parse(Console.ReadLine());
            switch (option)
            {
                case 1:
                    Console.Write(“Enter a visitor ID to add: “);
                    string visitorID = Console.ReadLine();
                    if (visitorIDs.Add(visitorID))
                    {
                        Console.WriteLine(“Visitor ID added.”);
                    }
                    else
                    {
                        Console.WriteLine(“Visitor ID already exists.”);
                    }
                    break;
                case 2:
                    Console.WriteLine(“Unique Visitor IDs:”);
                    if (visitorIDs.Count == 0)
                    {
                        Console.WriteLine(“No visitor IDs in the set.”);
                    }
                    else
                    {
                        foreach (string id in visitorIDs)
                        {
                            Console.WriteLine(“- ” + id);
                        }
                    }
                    break;
                case 3:
                    Console.WriteLine(“Exiting application.”);
                    return;
                default:
                    Console.WriteLine(“Invalid option. Please try again.”);
                    break;
            }
        }
    }
}

In a project scenario, let’s consider building a simple system to manage user profiles. This application will allow us to store user profiles with a unique username as the key and profile details as the value. This is a common requirement for applications that need to handle user data, and it can be efficiently managed using a Dictionary<TKey, TValue>.

Example: User Profile Manager

In this example, we’ll create a console application where user profiles can be added, retrieved, and displayed. Each profile will consist of a username (key) and user details (value).

using System;
using System.Collections.Generic;
class Program
{
    public static void Main()
    {
        // Creating a dictionary to store user profiles
        Dictionary<string, string> userProfiles = new Dictionary<string, string>();
        while (true)
        {
            Console.WriteLine(“\nUser Profile Manager”);
            Console.WriteLine(“1. Add User Profile”);
            Console.WriteLine(“2. Retrieve User Profile”);
            Console.WriteLine(“3. Display All User Profiles”);
            Console.WriteLine(“4. Exit”);
            Console.Write(“Choose an option: “);
            int option = int.Parse(Console.ReadLine());
            switch (option)
            {
                case 1:
                    Console.Write(“Enter username: “);
                    string username = Console.ReadLine();
                    if (userProfiles.ContainsKey(username))
                    {
                      Console.WriteLine(“Username already exists. Try another.”);
                    }
                    else
                    {
                        Console.Write(“Enter user details: “);                     
                        string userDetails = Console.ReadLine();
                        userProfiles[username] = userDetails;
                        Console.WriteLine(“User profile added.”);
                    }
                    break;
                case 2:
                    Console.Write(“Enter username to retrieve: “);
                    string userToRetrieve = Console.ReadLine();
                    if (userProfiles.TryGetValue(userToRetrieve, out string details))
                    {
                        Console.WriteLine($”User details for {userToRetrieve}: {details}”);
                    }
                    else
                    {
                        Console.WriteLine(“Username not found.”);
                    }
                    break;
                case 3:
                    Console.WriteLine(“All User Profiles:”);
                    if (userProfiles.Count == 0)
                    {
                        Console.WriteLine(“No user profiles found.”);
                    }
                    else
                    {
                      foreach (var profile in userProfiles)
                        {
                            Console.WriteLine($”{profile.Key}: {profile.Value}”);
                        }
                    }
                    break;
                case 4:
                    Console.WriteLine(“Exiting application.”);
                    return;
                default:
                    Console.WriteLine(“Invalid option. Please try again.”);
                    break;
            }
        }
    }
}

Course Video:
Course Video In English:
Task:

1. Basic Operations:
Write a C# program to create a HashSet<int> and perform basic operations such as adding, removing, and checking for the presence of elements.
Add values: 12, 36, 47, 67, 69
Remove values: 36, 67
Check if 47 is present in the set.

2. Duplicate Removal:
Write a method that takes a list of integers as input and returns a new list with duplicates removed using a HashSet.
Input list: 7, 8, 7, 10, 10, 12, 15, 8

3. Basic Usage:
Write a C# program to create a Dictionary<string, int> to store and display the names and ages of people. Include adding, updating, and removing entries.
Names and ages to add: “Alice” – 25, “Bob” – 30, “Charlie” – 22
Update the age of “Alice” to 26
Remove “Bob

4. Key and Value Iteration:
Given a Dictionary<string, string> representing a phone book, iterate over the dictionary to print all names and their corresponding phone numbers.
Phone book: “John” – “555-1234”, “Alice” – “555-5678”, “Bob” – “555-8765”

5. Finding a Value by Key:
Write a method that takes a Dictionary<int, string> and an integer key as input and returns the corresponding value. If the key does not exist, return “Key not found”.
Dictionary: 1 – “Math”, 2 – “Science”, 3 – “History”
Key to search: 2, 5

6. Group by Property:
Given a list of Student objects with properties Name and Grade, create a Dictionary<int, List<Student>> to group students by their grade.
Students: “Sara” – Grade 10, “Tom” – Grade 11, “Lily” – Grade 10, “Jack” – Grade 11

7. Basic Operations with List:
Write a C# program to create a List<string> and perform basic operations such as adding, inserting, removing, and checking for the presence of elements.
Add values: “Apple”, “Banana”, “Cherry”
Insert “Orange” at position 1
Remove “Banana”
Check if “Cherry” is in the list

8. Finding Elements:
Write a method that takes a List<string> and a string as input and returns all the indices where the string appears in the list.
List: “apple”, “banana”, “apple”, “cherry”, “apple”
String to search: “apple”

9. Write a program that converts an array of integers to a List<int> and performs some operations like reversing the list and finding the maximum and minimum values.
Array: 6, 12, 3, 9, 15, 1

10. Given a List<int>, write a method to sort the list in ascending and descending order.
List: 9, 3, 7, 1, 4

Collections

Frequently Asked Questions

Still have a question?

Let's talk

Collections in C# are a set of classes and interfaces used to store and manage groups of objects in a flexible and dynamic manner.

  • Generic Collections: List, Dictionary, Queue, Stack.
  • Non-Generic Collections: ArrayList, Hashtable.
  • Specialized Collections: NameValueCollection, StringCollection.

Lists are dynamic, allowing elements to be added or removed, whereas arrays have a fixed size.

A dictionary stores key-value pairs, allowing quick retrieval of values based on their associated keys.

IEnumerable provides a way to iterate over a collection using a foreach loop.

  • Stack: Last In, First Out (LIFO).
  • Queue: First In, First Out (FIFO).
  • Type safety.
  • Improved performance.
  • Reduced need for boxing/unboxing.
  • IList: Supports random access and manipulation of elements.
  • ICollection: Provides size, enumerator, and synchronization methods.

LINQ (Language-Integrated Query) allows querying collections using a readable and concise syntax.

Concurrent collections, such as ConcurrentDictionary, are thread-safe collections designed for multi-threaded operations.

C# provides several types of collections that fall into two main categories:

Generic Collections (e.g., List<T>, Dictionary<TKey, TValue>, Queue<T>, Stack<T>) – These collections are type-safe, meaning they store elements of a specified type.

Example of a List:

List<string> fruits = new List<string> { “Apple”, “Banana”, “Cherry” };

fruits.Add(“Mango”);

Console.WriteLine(string.Join(“, “, fruits));  // Output: Apple, Banana, Cherry, Mango

Non-Generic Collections (e.g., ArrayList, Hashtable, Queue) – These collections store elements of any type and are less type-safe.

Example of an ArrayList:

ArrayList list = new ArrayList();

list.Add(10);

list.Add(“Hello”);

Console.WriteLine(string.Join(“, “, list));  // Output: 10, Hello

Iqra Technology Academy provides free video tutorials in Hindi that cover the fundamentals of collections in C#. These tutorials include practical examples for using common collections like List, Dictionary, Queue, and Stack. The videos also explain the advantages of using collections over arrays.

Iqra Technology Academy offers a free online course in Hindi on collections in C#. This course covers various types of collections, their use cases, and how to manipulate them efficiently. You will learn to work with both generic and non-generic collections through real-world examples.