Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why output is 6 instead of other numbers?

Tags:

c#

list

lambda

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.

like image 659
Dragan Avatar asked Nov 28 '22 05:11

Dragan


1 Answers

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

like image 181
Jason W Avatar answered Nov 30 '22 20:11

Jason W