你能解释lambda表达式吗? [英] Can you explain lambda expressions?
问题描述
我实际上不会得到 lambda表达式。虽然他们从ALGOL的日子开始,直到最近,当Python和Ruby变得非常受欢迎,我才开始听到他们。现在C#有 =>
语法,我的世界中的人(.NET)越来越多地谈论lamdba表达式。
我读过维基百科上关于lambda演算的文章,但我不是一个数学家。我从一个实际的角度不真正理解它。我什么时候使用lambda表达式?为什么?我将如何知道这是我应该做什么?
你能展示一个如何解决lambda表达式的问题的例子,在一个前后格式?任何命令式语言都很好,但C#是最容易理解的。
基本上就C#表达式是一种创建委托(或表达式树,但现在让我们暂时离开)的简单方法。
在C#1中,我们只能从普通方法。
在C#2中,我们获得了匿名方法。
在C#3中,我们获得了lambda表达式,这就像更简洁的匿名方法。
当你想表达一些逻辑,值并返回一个值。例如,在LINQ的上下文中:
//只包含子项 - 一个谓词
var query = dataSource。 where(person => person.Age< 18)
//转换为名称序列 - 投影
.Select(person => person.Name);
有关这一点以及其他方面的更全面的讨论在关于关闭的文章。
I don't really get lambda expressions. While they've been around since the days of ALGOL, I didn't start hearing about them until fairly recently, when Python and Ruby became very popular. Now that C# has the
=>
syntax, people in my world (.NET) are talking about lamdba expressions more and more.I've read the Wikipedia article on the lambda calculus, but I'm not really a math guy. I don't really understand it from a practical perspective. When would I use lambda expressions? Why? How would I know that it's what I should be doing?
Can you show examples of how you would solve problems with lambda expressions, in a before-and-after format? Any imperative language is fine, but C# would be easiest for me to understand.
解决方案Basically as far as C# is concerned, lambda expressions are an easy way to create a delegate (or an expression tree, but let's leave those aside for now).
In C# 1 we could only create delegate instances from normal methods. In C# 2 we gained anonymous methods. In C# 3 we gained lambda expressions, which are like more concise anonymous methods.
They're particularly concise when you want to express some logic which takes one value and returns a value. For instance, in the context of LINQ:
// Only include children - a predicate var query = dataSource.Where(person => person.Age < 18) // Transform to sequence of names - a projection .Select(person => person.Name);
There's a fuller discussion of this - along with other aspects - in my article on closures.
这篇关于你能解释lambda表达式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!