C#•List & LINQ
C# List<T> and LINQ Queries: Where, Select, and Aggregate
Learn resizable List<T> operations and expressive declarative querying with Language Integrated Query (LINQ).
Syntax
List<int> numbers = new List<int> { 1, 2, 3 };
var evens = numbers.Where(x => x % 2 == 0).ToList();
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| List<T> | Generic Collection | Dynamically resizable array in System.Collections.Generic. |
| LINQ | Query Language | Functional querying methods in System.Linq. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing C# locally:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program {
public static void Main() {
List<string> languages = new List<string> { "C#", "Python", "Rust", "Java", "C++" };
// Adding dynamic elements
languages.Add("Go");
Console.WriteLine($"Total Languages: {languages.Count}");
// LINQ Query: Filter and transform
var filtered = languages
.Where(lang => lang.Length <= 3)
.Select(lang => lang.ToUpper())
.ToList();
Console.WriteLine("Short Languages (Length <= 3):");
foreach (var lang in filtered) {
Console.WriteLine($" -> {lang}");
}
}
}Expected Output:
Total Languages: 6 Short Languages (Length <= 3): -> C# -> C++ -> GO
How It Works: Step-by-Step
- Lines 7-10: Creates List<string> and adds element dynamically with Add().
- Lines 14-17: LINQ Where filters strings by length, and Select maps to uppercase.
Key Concepts
- List<T> provides fast O(1) indexed access and dynamic resizing.
- LINQ queries use deferred execution until ToList() or foreach is invoked.
Common Mistake: Evaluating expensive LINQ queries multiple times instead of calling ToList()
Without ToList(), LINQ re-executes the filter/select logic every time the query is enumerated.
❌ Incorrect
var query = list.Where(...); // Re-executes on every iteration!
✅ Correct
var query = list.Where(...).ToList(); // Materialized once into memory
Related C# Tutorials & Compiler
C# Dictionary<TKey, TValue>: Hash Table Operations
Store and retrieve key-value pairs using Dictionary<TKey, TValue> with TryGetValue.
C# HashSet<T> and ValueTuples (Multiple Return Values)
Deduplicate data with HashSet<T> and return multiple values using lightweight ValueTuples.
C# String Methods, String Interpolation, and StringBuilder
Master text manipulation with string methods, raw string literals, and StringBuilder.
C# Online Compiler
Open in Compilra IDE
Run and test C# on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.