Community for developers to learn, share their programming knowledge. Register!
C# Data Types

C# Collections Data Type


You can get training on our article about C# Collections Data Types, where we delve into the various collection types available in C#. As developers, understanding these collections is crucial for effective data management and processing within your applications. In this article, we will explore the different types of collections, their functionalities, and how to utilize them effectively in C# programming.

Overview of Collection Types in C#

In C#, a collection is a data structure that holds multiple items. Collections are essential for managing groups of objects and provide various functionalities that simplify data manipulation. The .NET framework offers several types of collections, which can be broadly categorized into two groups: generic and non-generic collections.

  • Generic Collections: Introduced in .NET 2.0, these collections provide type safety and improved performance. They include classes such as List<T>, Dictionary<TKey, TValue>, HashSet<T>, and more. The type parameter <T> allows you to specify the type of elements stored in the collection.
  • Non-generic Collections: These collections do not provide type safety and are less efficient than generic collections. Examples include ArrayList, Hashtable, and SortedList. They can store any type of object, but this flexibility comes at the cost of performance and type safety.

Using collections effectively can lead to cleaner, more maintainable code, and better performance in your applications.

Understanding Lists, Dictionaries, and Sets

Lists

The List<T> class is one of the most commonly used collection types in C#. It represents a strongly typed list of objects that can be accessed by index. Lists are dynamic in size, meaning they can grow or shrink as needed. Here’s a simple example of using a list:

List<string> fruits = new List<string>();
fruits.Add("Apple");
fruits.Add("Banana");
fruits.Add("Cherry");

// Accessing elements
Console.WriteLine(fruits[1]); // Output: Banana

Dictionaries

Dictionary<TKey, TValue> is another powerful collection type that stores key-value pairs. It allows for fast lookups based on keys, making it ideal for scenarios where you need to associate a unique identifier with a data element. Here's an example:

Dictionary<int, string> students = new Dictionary<int, string>();
students.Add(1, "John Doe");
students.Add(2, "Jane Smith");

// Accessing values by key
Console.WriteLine(students[1]); // Output: John Doe

Sets

HashSet<T> represents a collection of unique elements. It is particularly useful when you need to ensure that no duplicates are present. Here’s how you can use a HashSet:

HashSet<int> numbers = new HashSet<int>();
numbers.Add(1);
numbers.Add(2);
numbers.Add(2); // Duplicate will not be added

Console.WriteLine(numbers.Count); // Output: 2

Choosing the Right Collection Type

Selecting the appropriate collection type is crucial for application performance and maintainability. Here are some guidelines to help you choose:

  • Use Lists when you need an ordered collection of items that can contain duplicates and where you frequently access items by index.
  • Opt for Dictionaries when you have a set of unique keys and need to quickly retrieve values associated with those keys.
  • Choose Sets when you need to manage a collection of unique elements, and the order of elements is not a concern.

Consider the specific requirements of your application, such as performance needs, memory usage, and the operations you need to perform on the collection, to make an informed decision.

Iterating Through Collections

Iterating through collections is a fundamental operation. C# provides several ways to iterate over collections, including foreach loops, for loops, and LINQ queries.

Using foreach

The foreach loop is the most straightforward way to iterate through collections. Here’s a quick example using a list:

List<string> colors = new List<string> { "Red", "Green", "Blue" };

foreach (string color in colors)
{
    Console.WriteLine(color);
}

Using LINQ

LINQ (Language Integrated Query) offers a powerful method for querying collections. For example, if you want to filter a list of integers to find only the even numbers, you can do so with LINQ:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6 };
var evenNumbers = numbers.Where(n => n % 2 == 0);

foreach (var number in evenNumbers)
{
    Console.WriteLine(number); // Output: 2, 4, 6
}

Modifying Collections: Add, Remove, Clear

Modifying collections is a common task in programming. Let’s explore how to manipulate collections.

Adding Elements

You can add elements to a collection using methods like Add(), AddRange(), or Insert(). For example, to add multiple items to a list:

List<string> vegetables = new List<string> { "Carrot", "Potato" };
vegetables.AddRange(new List<string> { "Tomato", "Cucumber" });

Removing Elements

To remove elements, you can use methods like Remove(), RemoveAt(), or Clear(). For instance, to remove an item from a list:

vegetables.Remove("Potato"); // Removes Potato

Clearing Collections

If you need to remove all elements from a collection, the Clear() method is your best friend:

vegetables.Clear(); // Removes all items from the list

Using LINQ with Collections

LINQ is an essential feature in C# that allows for querying collections in a readable and concise way. It supports a wide range of operations, such as filtering, sorting, and grouping.

You can use LINQ methods like Select(), Where(), and OrderBy() to work with collections efficiently. For example:

List<int> scores = new List<int> { 90, 70, 80, 60 };
var highScores = scores.Where(s => s > 75).OrderByDescending(s => s);

foreach (var score in highScores)
{
    Console.WriteLine(score); // Output: 90, 80
}

LINQ not only simplifies your code but also enhances its readability, making it easier to understand the intent of your queries.

Summary

In this article, we explored the various C# Collection Data Types, including lists, dictionaries, and sets. We discussed how to choose the right collection type based on application needs, iterating through collections using different methods, and modifying collections with various operations. Additionally, we highlighted the power of LINQ for querying collections efficiently.

Understanding and effectively utilizing these collection types is essential for any developer looking to enhance their data management skills in C#. Whether you are building a simple application or a complex system, mastering collections in C# will undoubtedly improve your coding capabilities and performance. For further information, the official Microsoft documentation on collections provides a wealth of resources to continue your learning journey.

Last Update: 11 Jan, 2025

Topics:
C#
C#