Aggregation Methods
Method | Description | SQL equivalents |
|---|---|---|
| Returns the number of elements in the input sequence, optionally satisfying a predicate | |
| Returns the smallest or largest element in the sequence | |
| Calculates a numeric sum or average over elements in the sequence | |
| Performs a custom aggregation | Exception thrown |
Count and LongCount
Argument | Type |
|---|---|
Source sequence | |
Predicate (optional) | |
Count simply enumerates over
a sequence, returning the number of items:
int fullCount = new int[] { 5, 6, 7}.Count(); // 3The internal implementation of Enumerable.Count tests the input sequence to
see whether it happens to implement ICollection<T>. If it does, it simply
calls ICollection<T>.Count.
Otherwise, it enumerates over every item, incrementing a
counter.
You can optionally supply a predicate:
int digitCount = "pa55w0rd".Count (c => char.IsDigit (c)); // 3
LongCount does the same job
as Count, but returns a 64-bit
integer, allowing for sequences of greater than 2 billion
elements.
Min and Max
Argument | Type |
|---|---|
Source sequence | |
Result selector (optional) | |
Min and Max return the smallest or largest element
from a sequence:
int[] numbers = { 28, 32, 14 };
int smallest = numbers.Min(); // 14;
int largest = numbers.Max(); // 32;If you include a selector
expression, each element is first projected:
int smallest = numbers.Max (n => n % 10); // 8;
A selector ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access