You are currently viewing A Comprehensive Guide to C# Collections: Explained with Code Examples

A Comprehensive Guide to C# Collections: Explained with Code Examples

  • Post author:
  • Post category:C#
  • Post comments:0 Comments
  • Post last modified:May 16, 2024

Introduction to C# Collections

In C#, collections are fundamental for managing and organizing data efficiently. Understanding different types of collections and their usage is crucial for every C# developer. In this tutorial, we will explore various C# collections, including arrays, lists, dictionaries, and more, with code examples to illustrate their implementation and usage.

1. Arrays

Arrays are one of the simplest forms of collections in C#. They are fixed-size collections of elements of the same type.

// Declaration and initialization of an array
int[] numbers = new int[5] { 1, 2, 3, 4, 5 };

// Accessing elements of an array
Console.WriteLine(numbers[0]); // Output: 1

2. Lists

Lists provide dynamic resizing and more flexibility compared to arrays. They can grow or shrink in size as needed.

// Declaration and initialization of a list
List<string> names = new List<string>() { "Alice", "Bob", "Charlie" };

// Adding elements to a list
names.Add("David");

// Accessing elements of a list
Console.WriteLine(names[0]); // Output: Alice

3. Dictionaries

Dictionaries store key-value pairs and are useful for quick lookups based on keys.

// Declaration and initialization of a dictionary
Dictionary<string, int> ages = new Dictionary<string, int>()
{
    { "Alice", 30 },
    { "Bob", 25 },
    { "Charlie", 35 }
};

// Adding elements to a dictionary
ages["David"] = 40;

// Accessing elements of a dictionary
Console.WriteLine(ages["Alice"]); // Output: 30

4. Queues

Queues follow the First-In-First-Out (FIFO) principle, where elements are added to the end and removed from the beginning.

// Declaration and initialization of a queue
Queue<int> queue = new Queue<int>();

// Enqueue elements to the queue
queue.Enqueue(1);
queue.Enqueue(2);
queue.Enqueue(3);

// Dequeue elements from the queue
int dequeuedItem = queue.Dequeue(); // dequeuedItem = 1

5. Stacks

Stacks follow the Last-In-First-Out (LIFO) principle, where elements are added and removed from the top.

// Declaration and initialization of a stack
Stack<int> stack = new Stack<int>();

// Push elements onto the stack
stack.Push(1);
stack.Push(2);
stack.Push(3);

// Pop elements from the stack
int poppedItem = stack.Pop(); // poppedItem = 3

Conclusion

In this tutorial, we have covered the basics of C# collections, including arrays, lists, dictionaries, queues, and stacks. Understanding these collection types and their usage will empower you to efficiently manage and manipulate data in your C# applications. Experiment with these collections in your projects to gain hands-on experience and deepen your understanding further.

Leave a Reply