C#:C# List<T> and LINQ Queries: Where, Select, and Aggregate
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:

ParameterTypeDescription
List<T>Generic CollectionDynamically resizable array in System.Collections.Generic.
LINQQuery LanguageFunctional querying methods in System.Linq.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test C# on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C# Online Compiler