【问题标题】:s => s == 'w' - Help me understand this line of code [duplicate]s => s == 'w' - 帮助我理解这行代码 [重复]
【发布时间】:2018-07-05 10:28:54
【问题描述】:

我是 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();

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

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();

我看不到 's' 被声明为 char 变量,我不明白它在这里做了什么。谁能向我解释一下s =&gt; s == 'w' 做了什么?

是的,我试过用谷歌搜索这个。但我似乎找不到答案。

提前谢谢你:)

【问题讨论】:

  • 你应该用谷歌搜索的词是c# lambda expressions
  • 它是一个匿名函数,它接受一个参数s 并检查'w' 是否相等
  • 它的内容是:'集合中的一个项目 s 进入一个布尔值,将其与 x 进行比较'

标签: c#


【解决方案1】:

这是lambda expression

在这种情况下,它声明了一个anonymous delegate,该anonymous delegate 被传递给Count,其this overload 的签名指定了一个Func&lt;T, bool&gt;,它是一个匿名函数的类型表示,它接受一个T(对象的类型在集合)并返回布尔值。 Count() 这里将对集合中的每个对象执行此函数,并计算它返回了多少次 true

【讨论】:

    【解决方案2】:

    str.Count(s =&gt; s == 'w') 基本上是这样说的缩写:

    result = 0;
    foreach (char s in str)
    {
        if (s == 'w')
        {
            result += 1;
        }
    }
    return result;
    

    【讨论】:

      【解决方案3】:

      s =&gt; s == 'w' 是带有 lambda 表达式的谓词委托,

      str.Count(s =&gt; s == 'w') 只计算字符w 的出现次数

      【讨论】:

        猜你喜欢
        • 2010-11-12
        • 2011-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-26
        • 2013-06-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多