s => s =='w' - 帮助我理解这行代码

Ame*_*Ame 0 c#

我是C#的新手和一般的编码,对我正在做的一项练习有疑问.我正在关注w3resource的练习,我遇到了一个挑战,我必须解决这个问题:"编写一个C#程序来检查给定的字符串是否包含1到3次'w'字符."

我的解决方案是:

    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();
Run Code Online (Sandbox Code Playgroud)

这工作得很好,但我检查了他们的解决方案,它是这样的:

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();
Run Code Online (Sandbox Code Playgroud)

我看不到's'被声明为char变量,我不明白它在这里做了什么.任何人都可以向我解释一下是s => s == 'w'做什么的?

是的,我试过谷歌搜索这个.但我似乎无法找到答案.

先感谢您 :)

Tom*_*m W 5

这是一个lambda表达式.

在这种情况下,它声明一个匿名委托,它传递给Count,其重载的签名指定一个Func<T, bool>匿名函数的类型表示,它取一个T(集合中对象的类型)并返回bool.Count()这里将对集合中的每个对象执行此函数,并计算它返回的次数true.