.NET

Collections and LINQ Queries in C#

In modern C# programming, working with data collections is a common task. Understanding how to use Lists, Arrays, and Dictionaries, as well as querying them effectively using LINQ (Language Integrated Query), is a foundational skill for every .NET developer. This blog post will explore these essential topics with examples to help you get started.


Collections in C#

1. Arrays

An array is a fixed-size collection of elements of the same type. Arrays are suitable when you know the size of the collection at compile time.

Example:

int[] numbers = { 1, 2, 3, 4, 5 };
Console.WriteLine($"First number: {numbers[0]}");

Key Points:

  • Arrays have a fixed size.
  • Use the Length property to get the size of the array.
  • Elements are accessed using zero-based indexing.

2. Lists

Lists are dynamic collections that allow adding and removing elements at runtime. They belong to the System.Collections.Generic namespace and are type-safe.

Example:

List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
names.Add("Diana");
names.Remove("Bob");
Console.WriteLine($"First name: {names[0]}");

Key Points:

  • Lists grow or shrink dynamically.
  • Use methods like Add(), Remove(), and Contains() for manipulation.

3. Dictionaries

Dictionaries store key-value pairs and are perfect for scenarios where you need fast lookups.

Example:

Dictionary<string, int> scores = new Dictionary<string, int>
{
    { "Alice", 95 },
    { "Bob", 88 }
};

Console.WriteLine($"Alice's score: {scores["Alice"]}");

Key Points:

  • Keys must be unique.
  • Use ContainsKey() to check for a key’s existence.
  • Access values via their keys.

Introduction to LINQ

LINQ (Language Integrated Query) is a powerful feature in C# for querying and manipulating data collections. It provides a declarative syntax to work with collections such as arrays, lists, and dictionaries.


LINQ Syntax

LINQ comes in two flavors:

  1. Query Syntax: Inspired by SQL.
  2. Method Syntax: Uses extension methods.

Both produce the same results, and you can choose one based on your preference.


LINQ Examples

1. Querying an Array

Using LINQ to filter and sort an array:

int[] numbers = { 5, 3, 8, 1, 2 };

var evenNumbers = from num in numbers
                  where num % 2 == 0
                  orderby num
                  select num;

Console.WriteLine("Even Numbers: " + string.Join(", ", evenNumbers));

Equivalent Method Syntax:

var evenNumbers = numbers.Where(num => num % 2 == 0).OrderBy(num);
Console.WriteLine("Even Numbers: " + string.Join(", ", evenNumbers));

2. Querying a List

Using LINQ to find items in a list:

List<string> names = new List<string> { "Alice", "Bob", "Charlie", "Diana" };

var filteredNames = from name in names
                    where name.StartsWith("A")
                    select name;

Console.WriteLine("Names starting with A: " + string.Join(", ", filteredNames));

Equivalent Method Syntax:

var filteredNames = names.Where(name => name.StartsWith("A"));
Console.WriteLine("Names starting with A: " + string.Join(", ", filteredNames));

3. Querying a Dictionary

Using LINQ to work with dictionaries:

Dictionary<string, int> scores = new Dictionary<string, int>
{
    { "Alice", 95 },
    { "Bob", 88 },
    { "Charlie", 72 }
};

var highScores = from entry in scores
                 where entry.Value > 80
                 select entry;

foreach (var score in highScores)
{
    Console.WriteLine($"{score.Key}: {score.Value}");
}

Equivalent Method Syntax:

var highScores = scores.Where(entry => entry.Value > 80);

foreach (var score in highScores)
{
    Console.WriteLine($"{score.Key}: {score.Value}");
}

Combining LINQ with Collections

LINQ works seamlessly with collections like Lists, Arrays, and Dictionaries, allowing you to:

  • Filter data (Where clause).
  • Sort data (OrderBy and OrderByDescending).
  • Transform data (Select).
  • Aggregate data (Sum, Average, Count, etc.).

Example: Complex Query

List<int> numbers = new List<int> { 10, 20, 30, 40, 50 };

var result = numbers.Where(num => num > 20)
                    .Select(num => num * 2)
                    .OrderByDescending(num => num);

Console.WriteLine("Result: " + string.Join(", ", result));

Best Practices with Collections and LINQ

  1. Choose the Right Collection: Use Lists for dynamic data, Arrays for fixed-size data, and Dictionaries for key-value scenarios.
  2. Use LINQ for Readability: LINQ queries often make code cleaner and more expressive.
  3. Optimize Performance: Be cautious with large collections as LINQ queries can impact performance. Consider using ToList() or AsParallel() for optimization.

Conclusion

Collections and LINQ are essential tools for managing and querying data in C#. Understanding their strengths and how to use them effectively will significantly enhance your capabilities as a .NET developer. Practice combining Lists, Arrays, and Dictionaries with LINQ to unlock their full potential.

Danilo Cavalcante

Working with web development since 2005, currently as a senior programmer analyst. Development, maintenance, and integration of systems in C#, ASP.Net, ASP.Net MVC, .Net Core, Web API, WebService, Integrations (SOAP and REST), Object-Oriented Programming, DDD, SQL, Git, and JavaScript

Recent Posts

Exception Handling in C#: try-catch, finally, and Custom Exceptions

Exception handling is a critical part of writing robust and maintainable C# applications. It allows…

3 days ago

Do Docker Containers Take Up Space?

One of the common questions among Docker users is whether Docker containers consume disk space.…

6 months ago

How to Use “Order By” in C#

Sorting data is a common operation in programming, allowing you to organize information in a…

6 months ago

How to Split a String into an Array in C#

Splitting a string into an array of substrings is a common operation in C# programming,…

6 months ago

Starting the Docker Daemon: A Step-by-Step Guide

Starting the Docker daemon is the first step towards managing Docker containers and images on…

6 months ago

How to Serialize an Object in C# to JSON

Serializing an object to JSON (JavaScript Object Notation) format is a common task in C#…

6 months ago