CountBy
Applies a key-generating function to each element of a collection and returns a collection yielding unique keys and their number of occurrences in the original collection.
Parameters
Returns
Func<T, TKey> projection
IEnumerable<T> source
IEnumerable<(TKey Key, int Count)>
Usage
The projection
functions is used to creates a key to each element, after that, this method returns the number of occurrences of this key in original collection.
Counting even and odd numbers in a collection
//IEnumerable<int> source = { 1 .. 100 }
IEnumerable<(bool, int)> result = source.CountBy(value => value % 2 == 0);
// result = { (false, 50), (true, 50) }
Counting products by a price range
class Product {
int Id {get; set;}
string Name {get; set;}
double Price {get; set;}
}
// products:
// | Id | Name | Price |
// | 1 | Notebook | 800 |
// | 2 | Mouse | 20 |
// | 3 | Wallet | 40 |
// | 4 | Book | 10 |
// | 5 | Smartphone | 400 |
IEnumerable<(string, Product)> result =
products.CountBy(
product =>
product.Price > 200 ? "Expensive" : "Cheap")
// result = { ("Expensive", 2), ("Cheap", 3) }
Last updated
Was this helpful?