Day 7: Collections & LINQ Basics
Welcome to Day 7. Arrays in C# are fixed size, which makes them fast, but annoying when you don’t know exactly how many items you’ll have.
Enter the .NET Collections.
The Mighty List
List<T> is your go-to collection. It can grow and shrink dynamically. The <T> stands for “Type”, meaning it is a Generic collection. You specify the type when you create it.
// Using the System.Collections.Generic namespace
List<string> names = new List<string>();
names.Add("Alice");
names.Add("Bob");
Console.WriteLine(names[0]); // Alice
names.Remove("Bob"); // Removes bob
Console.WriteLine(names.Count); // 1
You can initialize them quickly, just like arrays:
var numbers = new List<int> { 10, 20, 30, 40 };
Dictionary<TKey, TValue>
Dictionaries (similar to Maps in JS / Hashes in Ruby) store key-value pairs. They offer incredibly fast lookups by key.
// Key: String (Username), Value: Int (Score)
var playerScores = new Dictionary<string, int>();
playerScores.Add("Alice_123", 9500);
// Or the shorthand syntax
playerScores["Bob_the_Builder"] = 4200;
Console.WriteLine(playerScores["Alice_123"]); // 9500
Enter LINQ (Language Integrated Query)
Here’s where C# flexes its muscles. LINQ is a massive feature that lets you query collections using a declarative syntax, similar to SQL.
It completely eliminates massive nested loops and if statements when filtering, sorting, or mapping data.
Make sure you have using System.Linq; at the top of your file!
var scores = new List<int> { 45, 92, 12, 88, 75, 99 };
// 1. Filtering (Where)
var passingScores = scores.Where(score => score >= 50);
// 2. Sorting (OrderBy)
var highToLow = scores.OrderByDescending(score => score);
// 3. Mapping (Select) - Like Array.map() in JS!
var curvedScores = scores.Select(score => score + 5);
// 4. Aggregations (Max, Min, Sum, Average)
int maxScore = scores.Max();
double avg = scores.Average();
Chaining LINQ
You can chain these commands together to create insanely powerful, readable queries!
// Find all passing scores, add a 5 point curve, and order them highest to lowest!
var finalGrades = scores
.Where(s => s >= 50)
.Select(s => s + 5)
.OrderByDescending(s => s)
.ToList(); // ToList executes the query immediately
Challenge for Day 7
Create a Product class with a Name and Price. Create a List<Product> with 5 items.
Use LINQ to:
- Find all products under $50.
- Select only the
Names of the products over $100.
Tomorrow: Delegates, Events & Lambdas.