You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
C# provides a rich set of collection types and LINQ (Language Integrated Query) for querying and transforming data. Together, they form one of the most powerful features of the language.
Fixed-size, strongly typed collections:
int[] numbers = { 1, 2, 3, 4, 5 };
string[] names = new string[3];
names[0] = "Alice";
// Multi-dimensional
int[,] matrix = { { 1, 2 }, { 3, 4 } };
// Jagged (array of arrays)
int[][] jagged = new int[3][];
jagged[0] = new[] { 1, 2, 3 };
A resizable, generic collection (the most commonly used):
var fruits = new List<string> { "Apple", "Banana", "Cherry" };
fruits.Add("Date");
fruits.Remove("Banana");
fruits.Insert(1, "Blueberry");
Console.WriteLine(fruits.Count); // 3
Console.WriteLine(fruits.Contains("Apple")); // true
Key-value pairs with fast lookup:
var capitals = new Dictionary<string, string>
{
["UK"] = "London",
["France"] = "Paris",
["Germany"] = "Berlin"
};
// Safe lookup
if (capitals.TryGetValue("UK", out string? capital))
{
Console.WriteLine(capital); // London
}
| Type | Description | Use Case |
|---|---|---|
HashSet<T> | Unique elements, fast contains | Membership testing |
Queue<T> | First-in, first-out | Processing queues |
Stack<T> | Last-in, first-out | Undo operations, parsing |
LinkedList<T> | Doubly linked list | Frequent insertions/removals |
SortedSet<T> | Sorted unique elements | Ordered unique data |
SortedDictionary<K,V> | Sorted key-value pairs | Ordered lookup |
ConcurrentDictionary<K,V> | Thread-safe dictionary | Multi-threaded access |
// Traditional
var list = new List<int> { 1, 2, 3 };
// Collection expressions (C# 12+)
List<int> list2 = [1, 2, 3];
int[] array = [4, 5, 6];
// Spread operator (C# 12+)
List<int> combined = [..list2, ..array, 7, 8, 9];
LINQ (Language Integrated Query) lets you query collections using SQL-like syntax directly in C#:
var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Query syntax
var evenNumbers = from n in numbers
where n % 2 == 0
orderby n descending
select n;
// Method syntax (more common)
var evenNumbers2 = numbers
.Where(n => n % 2 == 0)
.OrderByDescending(n => n)
.ToList();
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.