I am trying to understand lambda expression as a parameter
When we use Linq's Count
:
string s = "hello";
int count = s.Count(x => x == 'h');
How does it know x
is element of s
?
I am trying to understand lambda expression as a parameter
When we use Linq's Count
:
string s = "hello";
int count = s.Count(x => x == 'h');
How does it know x
is element of s
?
Just imagine it as loop iterating over elements of collection and applying given lamba to each element:
var count = 0;
foreach(var x in s)
if(x == 'h')
count++;
or using lambda expression:
Func<char, bool> predicate = (c) => c == 'h';
var count = 0;
foreach(var x in s)
if(predicate(c))
count++;
And here's source code for LINQ Count
method:
public static int Count<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
if (source == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
}
if (predicate == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.predicate);
}
int count = 0;
foreach (TSource element in source)
{
checked
{
if (predicate(element))
{
count++;
}
}
}
return count;
}
So you can see it almost the same as previous implementation, but it's using generic parameter TSource
instead hard coded char
.