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 will explore the definition and use of generic collections in C#. Generic collections are classes that enable you to store and manipulate collections of objects in a type-safe manner, without the need for casting or boxing.
C# provides several built-in generic collection classes in the System.Collections.Generic
namespace. Some commonly used generic collections are List<T>
, Dictionary<TKey, TValue>
, Queue<T>
, and Stack<T>
. These generic collections provide a more efficient and type-safe alternative to non-generic collections, like ArrayList
and Hashtable
.
List<T>
The List<T>
is a dynamic array, which can store a collection of items of the same type. It automatically resizes itself when necessary. Here's an example of how to use a List<T>
:
using System.Collections.Generic; List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; // Add an item numbers.Add(6); // Remove an item numbers.Remove(3); // Access an item by index int secondNumber = numbers[1]; // 2 // Iterate over the list foreach (int number in numbers) { Console.WriteLine(number); }
Dictionary<TKey, TValue>
The Dictionary<TKey, TValue>
is a collection of key-value pairs, where each key is unique. It allows you to efficiently look up values by their keys. Here's an example of how to use a Dictionary<TKey, TValue>
:
using System.Collections.Generic; Dictionary<string, int> ages = new Dictionary<string, int> { { "Alice", 30 }, { "Bob", 25 }, { "Charlie", 22 } }; // Add a key-value pair ages.Add("David", 28); // Remove a key-value pair ages.Remove("Alice"); // Access a value by its key int bobAge = ages["Bob"]; // 25 // Check if a key exists bool containsAlice = ages.ContainsKey("Alice"); // false // Iterate over the dictionary foreach (KeyValuePair<string, int> entry in ages) { Console.WriteLine($"{entry.Key}: {entry.Value}"); }
Queue<T>
The Queue<T>
is a first-in, first-out (FIFO) collection. It is useful when you need to store items in the order they arrive and process them in the same order. Here's an example of how to use a Queue<T>
:
using System.Collections.Generic; Queue<string> tasks = new Queue<string>(); // Enqueue items tasks.Enqueue("Wash dishes"); tasks.Enqueue("Do laundry"); tasks.Enqueue("Clean room"); // Dequeue an item string nextTask = tasks.Dequeue(); // "Wash dishes" // Peek at the next item without dequeuing string upcomingTask = tasks.Peek(); // "Do laundry"
Stack<T>
The Stack<T>
is a last-in, first-out (LIFO) collection. It is useful when you need to store items in a way that the most recent item is the first to be processed. Here's an example of how to use a Stack<T>
:
using System.Collections.Generic; Stack<string> history = new Stack<string>(); // Push items onto the stack history.Push("Page 1"); history.Push("Page 2"); history.Push("Page 3"); // Pop an item from the stack string lastVisitedPage = history.Pop(); // "Page 3"
How to define generic collections in C#:
public class GenericCollection<T> { private List<T> items = new List<T>(); public void AddItem(T item) { items.Add(item); } public void DisplayItems() { foreach (var item in items) { Console.WriteLine(item); } } }
C# generic collection example:
class Program { static void Main() { // Example of using a generic collection GenericCollection<int> intCollection = new GenericCollection<int>(); intCollection.AddItem(42); GenericCollection<string> stringCollection = new GenericCollection<string>(); stringCollection.AddItem("C# Generics"); intCollection.DisplayItems(); stringCollection.DisplayItems(); } }
C# List<T> generic collection:
List<string> stringList = new List<string>(); stringList.Add("C#"); stringList.Add("Generics");
Dictionary<T> in C# with generics:
Dictionary<int, string> keyValuePairs = new Dictionary<int, string>(); keyValuePairs.Add(1, "C#"); keyValuePairs.Add(2, "Dictionary");
C# generic collection initialization:
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
C# LINQ with generic collections:
var result = from item in stringList where item.Contains("C#") select item;