C# lambda 表达式可以有多个语句吗?

发布于 2024-11-01 02:45:11 字数 81 浏览 1 评论 0原文

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

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

Can a C# lambda expression include more than one statement?

(Edit: As referenced in several of the answers below, this question originally asked about "lines" rather than "statements".)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

我一直都在从未离去 2024-11-08 02:45:11

当然:

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

Sure:

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;
            }
        );
GRAY°灰色天空 2024-11-08 02:45:11

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

您可以使用大括号在 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; };

(I'm assuming you're really talking about multiple statements rather than multiple lines.)

You can use multiple statements in a lambda expression using braces, but only the syntax which doesn't use braces can be converted into an expression tree:

// 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; };
归属感 2024-11-08 02:45:11

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

您可能想询问多个陈述

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

请参阅文档

You can put as many newlines as you want in a lambda expression; C# ignores newlines.

You probably meant to ask about multiple statements.

Multiple statements can be wrapped in braces.

See the documentation.

王权女流氓 2024-11-08 02:45:11
Func<string, bool> test = (name) => 
{
   if (name == "yes") return true;
   else return false;
}
Func<string, bool> test = (name) => 
{
   if (name == "yes") return true;
   else return false;
}
臻嫒无言 2024-11-08 02:45:11

自 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; };

Since C# 7:

Single line statement:

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

Multiline statement:

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

although these are called local functions I think this looks a bit cleaner than the following and is effectively the same

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; };
叫嚣ゝ 2024-11-08 02:45:11

来自 Lambda 表达式(C# 编程指南)

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

From Lambda Expressions (C# Programming Guide):

The body of a statement lambda can
consist of any number of statements;
however, in practice there are
typically no more than two or three.

审判长 2024-11-08 02:45:11

另一个例子。

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.

Another Example.

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.
窗影残 2024-11-08 02:45:11

使用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);
    }
}

With c# 7.0
You can use like this also

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);
    }
}
舞袖。长 2024-11-08 02:45:11

假设您有一个类:

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

有关 解构文档中的元组

Let say you have a class:

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

With the C# 7.0 inside this class you can do it even without curly brackets:

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

and

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

would be the same as:

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

This also might be helpful if you need to write the a regular method or constructor in one line or when you need more then one statement/expression to be packed into one expression:

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

or

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

or

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

More about deconstruction of tuples in the documentation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文