List<int> lista = new List<int>() { 3, 4, 9, 8, 5, 6, 0, 3, 8, 3 };
int number = lista.Count(n => n <= 5);
I understand that we create list with those numbers... but how we get 6? dont understand actually what happend with (n => n <= 5) this.
This is counting the number of elements within the list where the number is less than or equal to 5. You get "6" because the elements 3, 4, 5, 0, 3, and 3 meet this criteria.
The n => n <= 5
can be confusing. It is a combination of lamba expression (n =>
expression) and the predicate/condition (n <= 5
).
When you call this Count<TSource>(...)
method, you are calling an extension method from Enumerable with this signature:
Count<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
For your case, the source
is "lista", and your predicate
is the condition of n <= 5
. Then, basically this code is running:
int count = 0;
foreach (TSource element in source) {
checked {
if (predicate(element)) count++;
}
}
return count;
This is how it iterates over your list counting only if the predicate condition matches what you provided.
Full Source: https://referencesource.microsoft.com/#system.core/system/linq/Enumerable.cs,1329
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With