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.
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]}");
Length
property to get the size of the array.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]}");
Add()
, Remove()
, and Contains()
for manipulation.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"]}");
ContainsKey()
to check for a key’s existence.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 comes in two flavors:
Both produce the same results, and you can choose one based on your preference.
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));
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));
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}");
}
LINQ works seamlessly with collections like Lists, Arrays, and Dictionaries, allowing you to:
Where
clause).OrderBy
and OrderByDescending
).Select
).Sum
, Average
, Count
, etc.).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));
Lists
for dynamic data, Arrays
for fixed-size data, and Dictionaries
for key-value scenarios.ToList()
or AsParallel()
for optimization.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.
Exception handling is a critical part of writing robust and maintainable C# applications. It allows…
One of the common questions among Docker users is whether Docker containers consume disk space.…
Sorting data is a common operation in programming, allowing you to organize information in a…
Splitting a string into an array of substrings is a common operation in C# programming,…
Starting the Docker daemon is the first step towards managing Docker containers and images on…
Serializing an object to JSON (JavaScript Object Notation) format is a common task in C#…