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

C# Generic Collection Definition And Use

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.

  • Introduction to Generic Collections

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.

  • Using 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);
}
  • Using 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}");
}
  • Using 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"
  • Using 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"
  1. How to define generic collections in C#:

    • Description: Generic collections are declared with type parameters to enable storage and manipulation of elements of specific types.
    • Code:
      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);
              }
          }
      }
      
  2. C# generic collection example:

    • Description: An example showcasing the use of a generic collection (List) with different data types.
    • Code:
      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();
          }
      }
      
  3. C# List<T> generic collection:

    • Description: List<T> is a dynamic array-based generic collection that allows flexible storage and manipulation of elements.
    • Code:
      List<string> stringList = new List<string>();
      stringList.Add("C#");
      stringList.Add("Generics");
      
  4. Dictionary<T> in C# with generics:

    • Description: Dictionary<TKey, TValue> is a key-value pair-based generic collection for efficient data retrieval.
    • Code:
      Dictionary<int, string> keyValuePairs = new Dictionary<int, string>();
      keyValuePairs.Add(1, "C#");
      keyValuePairs.Add(2, "Dictionary");
      
  5. C# generic collection initialization:

    • Description: Generic collections can be initialized using collection initializers, simplifying code.
    • Code:
      List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
      
  6. C# LINQ with generic collections:

    • Description: LINQ (Language-Integrated Query) enables powerful querying and manipulation of data within generic collections.
    • Code:
      var result = from item in stringList
                   where item.Contains("C#")
                   select item;