Skip to content

CSharp LINQ CoreOperators

Joe Care edited this page Dec 22, 2025 · 1 revision

C# LINQ: Core Operators (Where, Select, Count, First)

This lesson introduces a few core LINQ operators on in-memory collections.

Related wiki pages:

  • LINQ basics: CSharp-LINQ-Where-OrderBy.md
  • Collections: CSharpBible-Libraries.md

Official docs:


1. Example data

using System;
using System.Collections.Generic;
using System.Linq;

List<int> numbers = new() { 1, 2, 3, 4, 5 };
List<string> names = new() { "Alice", "Bob", "Charlie", "David" };

2. Select – project each element

IEnumerable<int> doubled = numbers.Select(n => n * 2);
Console.WriteLine(string.Join(", ", doubled)); // 2, 4, 6, 8, 10

Select transforms each element but keeps the same number of elements.


3. Where – filter elements

IEnumerable<string> namesStartingWithA = names.Where(n => n.StartsWith("A"));
Console.WriteLine(string.Join(", ", namesStartingWithA)); // Alice

Where keeps only elements that satisfy the predicate.


4. Count – number of elements

int countAll = numbers.Count();           // 5
int countEven = numbers.Count(n => n % 2 == 0); // 2

5. First – first element

int firstNumber = numbers.First();        // 1
string firstName = names.First();         // Alice

Use FirstOrDefault if the sequence might be empty.


6. Iterating with foreach

foreach (int n in numbers)
{
    Console.WriteLine(n);
}

For more about foreach and collections see Lesson14.12.2025.md (to be renamed to a foreach-focused title) and CSharp-Generics-Intro.md.


7. Next steps

  • Combine Where, Select, and OrderBy as shown in CSharp-LINQ-Where-OrderBy.md.
  • Apply these patterns to your own domain objects (e.g. lists of products, customers, etc.).

Clone this wiki locally