C# Tutorial
C# String
C# Array
C# Flow Control
C# Class and Object
C# Inheritance
C# Interface
C# Collection
C# Generic
C# File I/O
C# Delegate and Event
C# Exception
C# Process and Thread
C# ADO.NET Database Operations
In this tutorial, we'll cover the basics of collections in C#. Collections are a group of objects that can be used to store and manipulate data. C# provides a variety of collection classes such as List, Dictionary, HashSet, and others, which are part of the System.Collections
and System.Collections.Generic
namespaces.
Create a new C# Console Application project in Visual Studio and add the following namespace:
using System.Collections.Generic;
A List<T>
is a dynamic array that can grow or shrink in size. It stores elements in a linear sequence, allowing for efficient indexing and iteration.
// Create a List of integers List<int> numbers = new List<int>(); // Add elements to the list numbers.Add(1); numbers.Add(2); numbers.Add(3); // Remove an element from the list numbers.Remove(2); // Iterate through the list foreach (int number in numbers) { Console.WriteLine(number); }
A Dictionary<TKey, TValue>
is a collection of key-value pairs, where each key is unique. It allows you to store and retrieve values based on their keys.
// Create a Dictionary with string keys and string values Dictionary<string, string> countries = new Dictionary<string, string>(); // Add key-value pairs to the dictionary countries.Add("US", "United States"); countries.Add("UK", "United Kingdom"); countries.Add("JP", "Japan"); // Retrieve a value using its key string country = countries["US"]; Console.WriteLine(country); // Iterate through the dictionary foreach (KeyValuePair<string, string> entry in countries) { Console.WriteLine($"Key: {entry.Key}, Value: {entry.Value}"); }
A HashSet<T>
is an unordered collection of unique elements. It is optimized for fast set operations, such as adding, removing, and checking for the existence of elements.
// Create a HashSet of strings HashSet<string> names = new HashSet<string>(); // Add elements to the HashSet names.Add("John"); names.Add("Alice"); names.Add("Bob"); // Check if an element exists in the HashSet bool containsAlice = names.Contains("Alice"); Console.WriteLine(containsAlice); // Iterate through the HashSet foreach (string name in names) { Console.WriteLine(name); }
A Queue<T>
is a collection that represents a first-in, first-out (FIFO) queue. Elements are added to the end of the queue and removed from the front.
// Create a Queue of integers Queue<int> queue = new Queue<int>(); // Add elements to the queue queue.Enqueue(1); queue.Enqueue(2); queue.Enqueue(3); // Remove and return the element at the front of the queue int dequeued = queue.Dequeue(); Console.WriteLine(dequeued); // Peek at the element at the front of the queue without removing it int front = queue.Peek(); Console.WriteLine(front);
A Stack<T>
is a collection that represents a last-in, first-out (LIFO) stack. Elements are added to the top of the stack and removed from the top as well.
// Create a Stack of integers Stack<int> stack = new Stack<int>(); // Add elements to the stack stack.Push(1); stack.Push(2); stack.Push(3); // Remove and return the element at the top of the stack int popped = stack.Pop(); Console.WriteLine(popped); // Peek at the element at the top of the stack without removing it int top = stack.Top(); Console.WriteLine(top);
C# List collection example:
List<T>
class, a dynamic array that can grow or shrink in size, providing flexibility and functionality beyond simple arrays.List<int> myNumbers = new List<int>(); myNumbers.Add(42); myNumbers.Add(15); foreach (int number in myNumbers) { Console.WriteLine(number); }
Using arrays in C# collections:
int[] myArray = { 10, 20, 30 }; List<int> myList = new List<int>(myArray); foreach (int number in myList) { Console.WriteLine(number); }
Dictionary collection in C#:
Dictionary<TKey, TValue>
class, which represents a collection of key-value pairs.Dictionary<string, int> myDictionary = new Dictionary<string, int>(); myDictionary.Add("One", 1); myDictionary.Add("Two", 2); int value = myDictionary["Two"]; Console.WriteLine(value); // Output: 2
Sorting collections in C#:
Sort
for lists or OrderBy
for LINQ-based sorting.List<int> numbers = new List<int> { 5, 2, 8, 1, 7 }; numbers.Sort(); foreach (int number in numbers) { Console.WriteLine(number); }
Searching and filtering in C# collections:
Find
for lists or LINQ queries for more complex conditions.List<string> names = new List<string> { "Alice", "Bob", "Charlie" }; string result = names.Find(name => name.StartsWith("B")); Console.WriteLine(result); // Output: Bob
Manipulating items in C# collections:
Add
, Remove
, and Clear
for lists.List<string> fruits = new List<string> { "Apple", "Orange", "Banana" }; fruits.Add("Grapes"); if (fruits.Contains("Orange")) { fruits.Remove("Orange"); } fruits.ForEach(fruit => Console.WriteLine(fruit));