为了了解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表达式
发布评论