C# Collection

C# Collection

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.

  • Set up the environment

Create a new C# Console Application project in Visual Studio and add the following namespace:

using System.Collections.Generic; 
  • List

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); } 
  • Dictionary

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}"); } 
  • HashSet

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); } 
  • Queue

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); 
  • Stack

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); 

Examples

  1. C# List collection example:

    • Description: Demonstrating the usage of the List<T> class, a dynamic array that can grow or shrink in size, providing flexibility and functionality beyond simple arrays.
    • Code:
      List<int> myNumbers = new List<int>(); myNumbers.Add(42); myNumbers.Add(15); foreach (int number in myNumbers) { Console.WriteLine(number); } 
  2. Using arrays in C# collections:

    • Description: Illustrating how arrays can be used within collections to store and manage elements efficiently.
    • Code:
      int[] myArray = { 10, 20, 30 }; List<int> myList = new List<int>(myArray); foreach (int number in myList) { Console.WriteLine(number); } 
  3. Dictionary collection in C#:

    • Description: Introducing the Dictionary<TKey, TValue> class, which represents a collection of key-value pairs.
    • Code:
      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 
  4. Sorting collections in C#:

    • Description: Demonstrating how to sort elements in a collection using methods like Sort for lists or OrderBy for LINQ-based sorting.
    • Code:
      List<int> numbers = new List<int> { 5, 2, 8, 1, 7 }; numbers.Sort(); foreach (int number in numbers) { Console.WriteLine(number); } 
  5. Searching and filtering in C# collections:

    • Description: Showing how to search and filter elements in a collection using methods like Find for lists or LINQ queries for more complex conditions.
    • Code:
      List<string> names = new List<string> { "Alice", "Bob", "Charlie" }; string result = names.Find(name => name.StartsWith("B")); Console.WriteLine(result); // Output: Bob 
  6. Manipulating items in C# collections:

    • Description: Highlighting various methods to manipulate items within a collection, such as Add, Remove, and Clear for lists.
    • Code:
      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)); 

More Tags

query-performance sitecore splash-screen encoder can-bus android-activity inline nhibernate jupyter-notebook background-task

More Programming Guides

Other Guides

More Programming Examples