0

I am new to C# and coding in general and have a question on one exercise I'm doing. I am following the exercises on w3resource and I came across a challenge where I have to solve this: "Write a C# program to check if a given string contains 'w' character between 1 and 3 times."

My solution was this:

    var theString = Console.ReadLine(); 
    var theArray = theString.ToCharArray();
    int betweenOneAndThree = 0;

        for (int i = 0; i < theArray.Length - 1; i++)
        {
            if (theArray[i] == 'w')
                betweenOneAndThree++;
        }
        Console.WriteLine(betweenOneAndThree >= 1 && betweenOneAndThree <= 3);
        Console.ReadLine();

This worked just fine, but I checked their solution and it goes like this:

Console.Write("Input a string (contains at least one 'w' char) : ");
            string str = Console.ReadLine();
            var count = str.Count(s => s == 'w');
            Console.WriteLine("Test the string contains 'w' character  between 1 and 3 times: ");
            Console.WriteLine(count >= 1 && count <= 3);
            Console.ReadLine();

I can't see 's' being declared as a char variable and I do not understand what it does here. Can anyone please explain to me what s => s == 'w' does?

Yes, I have tried googling this. But I can't seem to find an answer.

Thank you in advance :)

Ame
  • 47
  • 6
  • 5
    The term you should google for is `c# lambda expressions` – Rotem Jul 05 '18 at 10:32
  • 1
    [Lambda Expressions](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/lambda-expressions) also [IEnumerable.Count](https://msdn.microsoft.com/en-us/library/bb535181(v=vs.110).aspx) – Steve Jul 05 '18 at 10:32
  • It is an anonymous function that takes one parameter `s` and checks equality against `'w'` – Vivick Jul 05 '18 at 10:33
  • It reads: 'an item s from the set goes to a bool that compares it to x' – TaW Jul 05 '18 at 12:11

3 Answers3

5

This is a lambda expression.

In this case it declares an anonymous delegate which is passed to Count, whose signature for this overload specifies a Func<T, bool> which is a typed representation of an anonymous function which takes a T (the type of the object in the collection) and returns bool. Count() here will execute this function against each object in the collection, and count how many times it returned true.

Tom W
  • 5,108
  • 4
  • 30
  • 52
1

str.Count(s => s == 'w') is basically a shortened way to say this:

result = 0;
foreach (char s in str)
{
    if (s == 'w')
    {
        result += 1;
    }
}
return result;
Steven
  • 1,996
  • 3
  • 22
  • 33
0

s => s == 'w' is Predicate delegate with lambda expression,

str.Count(s => s == 'w') simply counts the occurences of the characters w

Nitin Sawant
  • 7,278
  • 9
  • 52
  • 98