Collections & LINQ
Working with sequences and dictionaries
Introduction
In this lesson, you'll learn about collections & linq in C#. Coming from Python, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Python, you're familiar with working with sequences and dictionaries.
C# has its own approach to working with sequences and dictionaries, which we'll explore step by step.
The C# Way
Let's see how C# handles this concept. Here's a typical example:
using System.Collections.Generic;
using System.Linq;
// List<T>
var nums = new List<int> { 1, 2, 3, 4, 5 };
nums.Add(6);
// Dictionary<K,V>
var ages = new Dictionary<string, int> {
["Alice"] = 30, ["Bob"] = 25
};
ages["Charlie"] = 35;
// LINQ — like comprehensions
var doubled = nums.Select(n => n * 2).ToList();
var evens = nums.Where(n => n % 2 == 0).ToList();
int total = nums.Sum();
// Dictionary from LINQ
var squares = Enumerable.Range(0, 5)
.ToDictionary(n => n, n => n * n);
// Destructuring
var (first, second) = (nums[0], nums[1]);Comparing to Python
Here's how you might have written similar code in Python:
# List
nums = [1, 2, 3, 4, 5]
nums.append(6)
# Dict
ages = {"Alice": 30, "Bob": 25}
ages["Charlie"] = 35
# List comprehensions
doubled = [n * 2 for n in nums]
evens = [n for n in nums if n % 2 == 0]
total = sum(nums)
# Dict comprehension
squares = {n: n**2 for n in range(5)}
# Unpacking
first, *rest = numsYou may be used to different syntax or behavior.
Python list → C# List<T> (generic)
You may be used to different syntax or behavior.
Python dict → C# Dictionary<K,V>
You may be used to different syntax or behavior.
Python list/dict comprehensions → C# LINQ (Select/Where/ToDictionary)
You may be used to different syntax or behavior.
Python sum() → C# .Sum(); Python len() → .Count
Step-by-Step Breakdown
1. Generic Collections
C# collections use generics (List<int>) to enforce element types at compile time. Python lists can hold anything.
nums = [1, 2, 3]; nums.append(4)var nums = new List<int> { 1, 2, 3 };
nums.Add(4);2. LINQ vs Comprehensions
Python list comprehensions become LINQ method chains. Select=map, Where=filter, ToList() materializes the result.
[n * 2 for n in nums if n > 2]nums.Where(n => n > 2).Select(n => n * 2).ToList()3. Dictionary
C# Dictionary uses typed keys and values. The collection initializer syntax with [] closely resembles Python dict literals.
d = {"key": 1}; d.get("key", 0)var d = new Dictionary<string, int> { ["key"] = 1 };
d.GetValueOrDefault("key", 0);Common Mistakes
When coming from Python, developers often make these mistakes:
- Python list → C# List<T> (generic)
- Python dict → C# Dictionary<K,V>
- Python list/dict comprehensions → C# LINQ (Select/Where/ToDictionary)
Key Takeaways
- Python list → C# List<T>
- Python dict → C# Dictionary<K,V>
- List comprehensions → LINQ (Select/Where/ToList)
- sum/len → .Sum()/.Count