C# Collections and LINQ Basics
Introduction
Real programs work with groups of data. C# provides generic collections such as List and Dictionary, and LINQ (Language Integrated Query) adds readable methods for filtering, transforming, and sorting them. This tutorial covers both.
Prerequisites
- The .NET SDK installed
- Understanding of lambdas such as n => n * 2 is helpful
Step-by-Step Guide
Step 1: Store items in a List
List<T> is a resizable, ordered collection. Using a collection initializer, you can fill it when you create it.
var numbers = new List<int> { 5, 3, 8, 1, 9, 2 };
numbers.Add(7);
Console.WriteLine(numbers.Count); // 7
Console.WriteLine(numbers[0]); // 5Step 2: Look up values with a Dictionary
Dictionary<TKey, TValue> maps keys to values. Use TryGetValue to read a key that might not exist.
var ages = new Dictionary<string, int>
{
["Ava"] = 30,
["Ben"] = 25
};
if (ages.TryGetValue("Cy", out var age))
{
Console.WriteLine(age);
}
else
{
Console.WriteLine("Not found");
}Step 3: Filter, transform, and sort with LINQ
LINQ methods work on any collection and can be chained. Add using System.Linq if your project doesn't include it implicitly.
var evens = numbers.Where(n => n % 2 == 0).ToList();
var squares = numbers.Select(n => n * n).ToList();
var sorted = numbers.OrderBy(n => n).ToList();
Console.WriteLine(string.Join(", ", sorted)); // 1, 2, 3, 5, 7, 8, 9Step 4: Calculate aggregates
LINQ also provides Sum, Average, Min, Max, and Count.
Console.WriteLine(numbers.Sum()); // 35
Console.WriteLine(numbers.Max()); // 9
Console.WriteLine(numbers.Average()); // 5FAQs
- Is LINQ evaluated immediately?
- Many LINQ methods such as Where and Select use deferred execution: the query runs when you iterate the result or call ToList or ToArray, not when you write it.
- When should I use an array instead of a List?
- Use an array for a fixed number of items known up front. Use List when you need to add or remove items.
Summary
List and Dictionary cover most storage needs, and LINQ turns loops into short, readable queries. Remember that many LINQ queries run lazily until you enumerate them.
Comments
Log in or create a free account to join the discussion.