Aggregates and ToList
Count, Sum, and materialize.
Counting Elements
Count returns the number of elements in a sequence. With a predicate, it counts only matching elements.
It forces enumeration, so the whole sequence is walked to produce the total — an aggregate operation.
using System;
using System.Linq;
int[] nums = { 1, 2, 3, 4, 5 };
Console.WriteLine(nums.Count());
Console.WriteLine(nums.Count(n => n > 2));Summing Values
Sum adds up numeric values. On a numeric sequence it sums the elements; with a selector it sums a projected value from each element.
It returns the same numeric type as the source or selector result.
using System;
using System.Linq;
using System.Collections.Generic;
record Order(int Qty, decimal Price);
var orders = new List<Order> { new(2, 5m), new(3, 4m) };
decimal total = orders.Sum(o => o.Qty * o.Price);
Console.WriteLine(total);All lessons in this course
- Where and Filtering
- Select and Projection
- OrderBy and Grouping
- Aggregates and ToList