-1

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?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • Could you clarify what you mean by `how does it know x is element of s`? Do you not understand what lambda expression are? Do you not understand how they're being used in the context of the `Count()` method? Do you not understand how strings can be enumerated? – Patrick Tucci Jul 11 '21 at 14:44
  • There is no shortage of information on the site explaining lambda expressions. See duplicates. In your example, `x` is just the parameter for the anonymous method that the lambda represents; it "knows" the value because the caller, the iterator that `Count()` creates, _passes the value_, just like any caller would pass any value to any other method. – Peter Duniho Jul 12 '21 at 07:10

2 Answers2

1

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.

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
0

Because string implements IEnumerable<char>

TomCN
  • 22
  • 3