【问题标题】:Can a C# lambda expression have more than one statement?C# lambda 表达式可以有多个语句吗?
【发布时间】:2011-08-04 22:51:33
【问题描述】:

一个 C# lambda 表达式可以包含多个语句吗?

(编辑:正如以下几个答案中所引用的,这个问题最初询问的是“行”而不是“语句”。)

【问题讨论】:

  • 是的,您可以使用多行。我觉得把它作为一个完整的答案是不对的。
  • @Tesserex - 什么不能让它成为答案......你是对的!
  • @RQDQ 因为这是一个是或否的问题,所以我觉得它不值得从投票中产生的代表。

标签: c# lambda


【解决方案1】:

当然:

List<String> items = new List<string>();

var results = items.Where(i => 
            {
                bool result;

                if (i == "THIS")
                    result = true;
                else if (i == "THAT")
                    result = true;
                else
                    result = false;

                return result;
            }
        );

【讨论】:

    【解决方案2】:

    (我假设您实际上是在谈论多个语句而不是多行。)

    您可以使用大括号在 lambda 表达式中使用多个语句,但只有不使用大括号的语法才能转换为表达式树:

    // Valid
    Func<int, int> a = x => x + 1;
    Func<int, int> b = x => { return x + 1; };        
    Expression<Func<int, int>> c = x => x + 1;
    
    // Invalid
    Expression<Func<int, int>> d = x => { return x + 1; };
    

    【讨论】:

    • 我试图理解为什么 Func 允许大括号而 Expression 不允许。无论如何,表达式将被编译为 Func,有没有办法将多行逻辑添加到表达式树?如果没有,为什么有限制?
    • @Habeeb:“无论如何,表达式将符合 Func” 并非总是如此。很多时候,它根本就没有编译到委托中——只是作为数据进行检查。 .NET 4.0 中的表达式树确实能够通过 Expression.Block 包含多个语句,但 C# 语言 不支持这一点。可以,但这需要更多的设计/实施/测试工作。
    【解决方案3】:

    您可以在 lambda 表达式中添加任意数量的换行符; C# 忽略换行符。

    您可能想询问多个陈述

    多条语句可以用大括号括起来。

    请参阅documentation

    【讨论】:

    • 如果说 C# 平等对待所有空格(包括换行符)不是更准确吗?说它忽略换行符听起来有点误导 - 它看起来好像只是将它们完全剥离,并且您可以将关键字拆分为换行符或其他内容。
    【解决方案4】:

    从 C# 7 开始:

    单行语句:

    int expr(int x, int y) => x + y + 1; 
    

    多行语句:

    int expr(int x, int y) { int z = 8; return x + y + z + 1; };
    

    虽然这些被称为本地函数,但我认为这看起来比下面的更干净,并且实际上是相同的

    Func<int, int, int> a = (x, y) => x + y + 1;
    
    Func<int, int, int> b = (x, y) => { int z = 8; return x + y + z + 1; };
    

    【讨论】:

      【解决方案5】:
      Func<string, bool> test = (name) => 
      {
         if (name == "yes") return true;
         else return false;
      }
      

      【讨论】:

      • Func test = name => name=="yes";
      • Polity 正在展示问题所要求的多行格式,而不是娱乐打高尔夫球的建议。实施您的明智代码将使其“不是答案”!
      【解决方案6】:

      来自Lambda Expressions (C# Programming Guide)

      语句体 lambda 可以 由任意数量的语句组成; 然而,在实践中有 通常不超过两三个。

      【讨论】:

        【解决方案7】:

        另一个例子。

        var iListOfNumbers = new List<int>() { 1, 2, 3, 4, 5 };
        
        Func<List<int>, int> arithmeticSum = iList =>
        {
            var finalResult = 0;
                    
            foreach (var i in iList)
                finalResult = finalResult + i;
                    
            return finalResult;
        };
        
        Console.WriteLine(arithmeticSum.Invoke(iListOfNumbers));
        Console.WriteLine(arithmeticSum(iListOfNumbers));
        // The above two statements are exactly same.
        

        【讨论】:

          【解决方案8】:

          使用 c# 7.0 你也可以这样使用

          Public string ParentMethod(int i, int x){
              int calculation = (i*x);
              (string info, int result) InternalTuppleMethod(param1, param2)
              {
                  var sum = (calculation + 5);
                  return ("The calculation is", sum);
              }
          }
          

          【讨论】:

            【解决方案9】:

            假设你有一堂课:

                public class Point
                {
                    public int X { get; set; }
                    public int Y { get; set; }
                }
            

            使用此类中的 C# 7.0,即使没有大括号,您也可以做到:

            Action<int, int> action = (x, y) => (_, _) = (X += x, Y += y);
            

            Action<int, int> action = (x, y) => _ = (X += x, Y += y);
            

            将等同于:

            Action<int, int> action = (x, y) => { X += x; Y += y; };
            

            如果您需要在一行中编写常规方法或构造函数,或者当您需要将多个语句/表达式打包到一个表达式中时,这也可能会有所帮助:

            public void Action(int x, int y) => (_, _) = (X += x, Y += y);
            

            public void Action(int x, int y) => _ = (X += x, Y += y);
            

            public void Action(int x, int y) => (X, Y) = (X + x, Y + y);
            

            更多关于deconstruction of tuples in the documentation

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2018-02-24
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-05-27
              相关资源
              最近更新 更多