了解C#Lambda表达式 [英] understanding C# Lambda Expressions

查看:62
本文介绍了了解C#Lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了了解C#中的lambda表达式,我进行了大量的Google搜索.尽管人们提供了一些信息,但我不明白它是什么.谁能用以下代码解释我.这段代码可以使我理解,因为它是我的"上下文.

I have googled a lot to understand the lambda expressions in c#. Though people have given a handful of information, I couldn't understand what it is. Can any one explain me with the following code. This code can give me the understanding, since it is "my" context.

context.Authors.AddOrUpdate(x => x.Id,
    new Author() { Id = 1, Name = "Jane Austen" },
    new Author() { Id = 2, Name = "Charles Dickens" },
    new Author() { Id = 3, Name = "Miguel de Cervantes" }
    );

为什么不是"x => x"?

Why it is not "x=>x" ?

推荐答案

x => x 

x => {
    return x;
}

这是一个将x作为参数并返回x的函数,而

which is a function that takes x as a parameter and returns x, while

x => x.Id

x => {
    return x.Id;
}

这基本上意味着 AddOrUpdate 函数需要知道如何获取要添加或更新的实体的ID,您可以将lambda视为定义函数的紧凑方式,在大多数情况下,可以实际定义一个函数:

This basically means that the AddOrUpdate function needs to know how to get the Id of the entities it's adding or updating, you can think of lambdas as a compact way of defining functions, in most cases you can actually define a function:

int GetAuthorId(Author x) {
    return x.Id;
}

并使用该函数代替lambda:

and use the function in place of the lambda:

context.Authors.AddOrUpdate(GetAuthorId,
    new Author() { Id = 1, Name = "Jane Austen" },
    new Author() { Id = 2, Name = "Charles Dickens" },
    new Author() { Id = 3, Name = "Miguel de Cervantes" }
);

在AddOrUpdate函数内部,只要要查找作者的ID,它将运行传递Author作为参数的GetAuthorId

Inside the AddOrUpdate function, it will run the GetAuthorId passing an Author as a parameter whenever it wants to find an Author's Id

-编辑-

正如评论中正确指出的,我刚才所说的内容对 Func<> 是正确的,但对于 Expression< Func<>> 可以在此处

As correctly noted in the comments, what I just said is true for Func<>, but is NOT true for Expression<Func<>> you can read a little about the difference here

这篇关于了解C#Lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆