C# / C# Collections and Generics

Exploring Generic Collections

In this tutorial, you will explore the use of Generic Collections in C#. These versatile data structures can store any data type, providing both flexibility and type safety.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Introduces collections and generics to handle and manipulate data efficiently.

1. Introduction

In this tutorial, we'll explore the functionality and versatility of Generic Collections in C#. Generics allow you to define type-safe data structures, meaning that you can check for the data type at compile time, preventing common type mismatches.

By the end of this tutorial, you'll learn:
- What Generic Collections are and why they're useful
- How to use List, Dictionary, and other generic collections
- Best practices for working with Generic Collections

Prerequisites: Basic knowledge of C# programming language is required.

2. Step-by-Step Guide

Understanding Generic Collections

Generic collections are classes provided by the .NET Framework to store, retrieve, and manipulate data in a type-safe manner. The most commonly used Generic Collections are List, Dictionary, Queue, and Stack.

Using List

List can be thought of as a dynamic array. Here, T represents the type of elements in the list. Let's look at a simple example:

List<int> numbers = new List<int>();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);

In this example, we create a list of integers and add three elements to it.

3. Code Examples

Example 1: Using List

Let's explore how to use the List collection:

List<int> numbers = new List<int> {1, 2, 3, 4, 5}; // Initialize the list with some numbers
numbers.Add(6); // Add an item to the end of the list
numbers.Insert(0, 0); // Insert an item at a specific position

foreach (int number in numbers) // Traverse the list
{
    Console.WriteLine(number); // Output: 0, 1, 2, 3, 4, 5, 6
}

Example 2: Using Dictionary

A Dictionary stores key-value pairs. Let's see it in action:

Dictionary<string, int> ages = new Dictionary<string, int>(); // Create a new dictionary
ages.Add("John", 28); // Add a key-value pair
ages.Add("Jane", 30); // Add another key-value pair

foreach (KeyValuePair<string, int> entry in ages) // Traverse the dictionary
{
    Console.WriteLine($"Name: {entry.Key}, Age: {entry.Value}"); // Output: Name: John, Age: 28 and Name: Jane, Age: 30
}

4. Summary

In this tutorial, we've learned about Generic Collections in C#, why they're useful, and how to use List and Dictionary. Practice using these collections and explore others like Queue and Stack.

For further learning, consider reading Microsoft's official documentation on Generic Collections.

5. Practice Exercises

  1. Exercise 1: Create a List of your favorite movies and print them out.
  2. Exercise 2: Create a Dictionary that stores student names and their grades. Print out each student's name and grade.

Solutions:

  1. Solution 1:
List<string> movies = new List<string> {"Inception", "The Dark Knight", "Interstellar"};
foreach (string movie in movies)
{
    Console.WriteLine(movie);
}
  1. Solution 2:
Dictionary<string, string> grades = new Dictionary<string, string> {{"John", "A"}, {"Jane", "B"}};
foreach (KeyValuePair<string, string> entry in grades)
{
    Console.WriteLine($"Name: {entry.Key}, Grade: {entry.Value}");
}

For further practice, consider creating and manipulating a Stack or Queue.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

JavaScript Minifier & Beautifier

Minify or beautify JavaScript code.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help