Lambda 表达式语法

发布于 2024-10-18 15:05:37 字数 273 浏览 1 评论 0原文

使用 LINQ 时,是否必须使用 lambda 表达式,或者 lambda 表达式是可选的吗?

在 lambda 表达式中,始终使用符号 =>。这是什么意思?

 customers.Where(c => c.City == "London"); 

这里使用了 c => 但为什么呢? 使用c =>有什么意义。请详细讨论,因为我不知道lambda。

Is it mandatory that lambda expression need to use when LINQ will be used, or are lambda expressions optional?

In lambda expressions, the sign => is always used. What does it mean?

 customers.Where(c => c.City == "London"); 

Here c => is used but why?
What kind of meaning of using c =>. Please discuss in detail because I don't know lambda.

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

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

发布评论

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

评论(7

云仙小弟 2024-10-25 15:05:37

不,您不必使用 lambda 表达式。例如,您的 Where 示例可以写为:

private static bool IsLondon(Customer customer)
{
    return customer.City == "London";
}

...

var londoners = customers.Where(IsLondon);

当然,这是假设 LINQ to Objects。对于 LINQ to SQL 等,您需要构建一个表达式树。

至于为什么是“==”总是在 lambda 表达式中使用,这只是因为这就是运算符的编写方式 - 这就像问为什么使用“+”进行加法一样。

“c => ...”的 lambda 表达式实际上为 lambda 表达式提供了一个名为 c参数...在这种情况下,泛型类型推断提供了 >类型c。正文提供要执行的操作或一些计算以返回基于 c 的值。

lambda 表达式的完整描述超出了本答案的范围。然而,作为我的书的公然插件,它们在《C# 深度》第 9 章中进行了详细介绍。

No, you don't have to use a lambda expression. For example, your Where example could be written as:

private static bool IsLondon(Customer customer)
{
    return customer.City == "London";
}

...

var londoners = customers.Where(IsLondon);

That's assuming LINQ to Objects, of course. For LINQ to SQL etc, you'd need to build an expression tree.

As to why "=>" is always used in a lambda expression, that's simply because that's the way the operator is written - it's like asking why "+" is used for addition.

A lambda expression of "c => ..." is effectively giving the lambda expression a parameter called c... in this case generic type inference provides the type of c. The body provides either an action to perform or some calculation to return a value based on c.

A full-blown description of lambda expressions is beyond the scope of this answer. As a blatant plug for my book, however, they're covered in detail in chapter 9 of C# in Depth.

难以启齿的温柔 2024-10-25 15:05:37

lambda 表达式

c => c.City == "London"

是类似的简写,

bool IsCustomerInLondon(Customer c)
{
  return (c.City == "London");
}

它只是编写返回值的简单函数的一种非常简洁的方式。它被称为“匿名函数”,因为它从未被分配名称或正式定义(参数类型和返回类型是从上下文推断的)。

(实际上,它不仅仅是简写;lambda 表达式与其他一些称为 闭包,这是非常酷且强大的工具。)

The lambda expression

c => c.City == "London"

is shorthand for something like

bool IsCustomerInLondon(Customer c)
{
  return (c.City == "London");
}

It's just a very concise way of writing a simple function that returns a value. It's called an "anonymous function" because it's never assigned a name or a formal definition (the parameter types and the return type are inferred from the context).

(Actually, it's not just shorthand; lambda expressions are related to some other constructs called closures, which are very cool and powerful tools.)

孤独患者 2024-10-25 15:05:37

将 lambda 视为匿名函数。
我将尝试用以下代码来解释它。

public bool IsLondon(Customer customer)
{
    return customer.City == "London";
}

现在我们去掉函数名并去掉大括号:

public bool Customer customer    
    return customer.City == "London";

我们不需要返回类型,因为编译器能够从表达式推断出类型:

 customer.City == "London";

以同样的方式编译器知道输入类型,所以我们不需要指定它。

所以基本上,我们剩下的是

customer
   return customer.City == "London";

C# 中的 lambda 语法基本上是:

(parameter list) => "expression"

您也可以编写“多行”表达式,但是您必须用花括号将代码括起来。此外,您还需要像平常一样使用“return”语句。

Think about lambdas as anonymous of functions.
I'll try to explain it with following code.

public bool IsLondon(Customer customer)
{
    return customer.City == "London";
}

Now we strip down function name and get rid of braces:

public bool Customer customer    
    return customer.City == "London";

We don't need return type, because compiler is able to deduce type from expression:

 customer.City == "London";

In the same manner compiler knows about input type, so we don't need to specify it.

So basically, what we left with is

customer
   return customer.City == "London";

And lambda syntax in c# is basically:

(parameter list) => "expression"

You can also write "multi-line" expressions, but then you have to surround your code with curly braces. Also you will need to use "return" statement, like you usually do.

燕归巢 2024-10-25 15:05:37

乔恩已经回答了,
但我想补充一点。

在您给出的示例中,想象 Linq 循环遍历所有客户,
c 只是对可枚举中每一项的引用:

var result = new List<Customer>();
foreach(var c in customers)
{
     if (c.City == "London")
        result.Add(c);   
}
return result;

它是一个与其他变量一样的变量,它不必是单个命名的变量,
但这只是某种约定。

Jon already answered,
but I'd like to add this.

In the example you have given, imagine Linq looping over all customers,
and c is simply a reference to each item in the enumerable:

var result = new List<Customer>();
foreach(var c in customers)
{
     if (c.City == "London")
        result.Add(c);   
}
return result;

It's a variable like any other, it does not have to be a single named one,
but it's just a convention of some sort.

临风闻羌笛 2024-10-25 15:05:37

您不需要在 LInq to sql 或 Entities 上使用 lambda 表达式;这是您的代码的另一种方式;

你编码:

customers.Where(c => c.City == "London");

另一种方式;

  var query = from cs in customers
              where cs.City == "London"
              select cs;

这是另一种方式。这取决于你。

you do not need to use lambda expressions on Lİnq to sql or Entities; here is an alternative way of your code;

you code :

customers.Where(c => c.City == "London");

the other way;

  var query = from cs in customers
              where cs.City == "London"
              select cs;

this is the another way. it is up to you.

习ぎ惯性依靠 2024-10-25 15:05:37

Lambda 和 linq 是完全分开的。您可以使用其中一个而不使用另一个(linq 的某些部分依赖于 lambda 表达式,但我们希望保持简单:-))

lambda 表达式是匿名的
可以包含表达式的函数
和语句,并且可用于
创建委托或表达式树
类型。

这是来自 MSDN 的。 (http://msdn.microsoft.com/en-us/library/bb397687.aspx)

为了使其简短(它要复杂得多),您可以使用 lambda 表达式来创建本地函数。 => 之前放置的内容(在您的示例中,c)将是函数的参数。返回类型由 C# 编译器“发现”。

<代码>c => c.City == "London" 几乎等同于:(

delegate (TheObjectTypeOfC c) {
   return c.City == London
};

区别在于有些 lambda 表达式是委托,也是表达式,但请忽略这一点,一段时间内你不会需要它)

如果/当编译器无法推断参数的类型,您可以强制它们: (MyObject p) =>; p.SomeProperty!= null。这里你告诉编译器 p 是一个参数。

虽然在这里我向您展示了所谓的“表达式 lambda”,您甚至可以执行“语句 lambda”:(

p => {
   for (int i = 0; i < 10; i++) {
       if (p.SomeProperty == 0) {
          return true;
       }
   }

   return false;
}

我不会告诉您表达式 lambda 和语句 lambda 之间的“幕后”区别是什么。如果您想知道他们,请阅读我之前指出的 msdn 页面)

Lambda and linq are quite separate. You can use one without using the other (there are parts of linq that depend on lambda expressions, but we want to keep it simple :-) )

A lambda expression is an anonymous
function that can contain expressions
and statements, and can be used to
create delegates or expression tree
types.

This was from MSDN. (http://msdn.microsoft.com/en-us/library/bb397687.aspx )

To make it short (it's much more complex) you can use a lambda expression to make a local function. what you put before the => (in your example the c) will be the parameter of the function. The return type is "discovered" by the C# compiler.

c => c.City == "London" is nearly equivalent to:

delegate (TheObjectTypeOfC c) {
   return c.City == London
};

(the difference is that some lambda expression are delegates and also expressions, but please ignore this, you won't need it for some time)

If/when the compiler isn't able to infer the types of the parameters, you can force them: (MyObject p) => p.SomeProperty != null. Here you are telling the compiler that p is a parameter.

While here I showed you what are called "expression lambdas", you can even do "statement lambdas":

p => {
   for (int i = 0; i < 10; i++) {
       if (p.SomeProperty == 0) {
          return true;
       }
   }

   return false;
}

(I won't tell you what are the "behind the scenes" differences between expression lambdas and statement lambdas. If you want to know them, read the msdn page I pointed before)

爱的故事 2024-10-25 15:05:37

不,根本没有必要。

我们有两种编写 LINQ 查询的方法。

一种是查询方法,另一种是构建器方法。您只需要在构建器方法的情况下放置 lambda 表达式。
例如,如果我们想从某些 Students 对象中查找所有分数超过 70 分的学生。
但我们可以使用以下语法在 LINQ 中完成此操作

   var data = from p in stdList
   where p.marks > 70
   select p;


var data = stdList.Where(p=>p.marks > 70);

后来的方法是构建器方法,在Where函数中,我们传递lambda表达式。

Lambda 表达式只是执行操作的捷径,您始终可以使用 LINQ 查询,但如果您想避免仅应用简单条件的整个查询语法,您可以在 lambda 表达式中使用 LINQ 构建器方法(需要 lambda 表达式),您始终定义一些别名,然后执行您的操作。

至于=>就运算符而言,它的工作原理与赋值运算符类似。
例如:

(p) => p.Gender == “F”
It means  “All persons  p, such that person’s Gender is F”

在一些文献中这被称为“谓词”。另一个文献术语是“Projection”,

(p) => p.Gender ? “F” : “Female”
“Each person p becomes string “Female” if Gender is “F”” 

这是投影,它使用三元运算符。
虽然我用非常基本的例子进行了解释,但我希望这会对您有所帮助。 。 。 :)

No it is not necessary at all.

We have two ways to write LINQ queries.

One is query method and other is builder method. You only need to put lambda expression in case of builder method.
For example, if we want to find all those students from some Students object that have more marks than 70.
but we can do this thing in LINQ with following syntax

   var data = from p in stdList
   where p.marks > 70
   select p;

or
var data = stdList.Where(p=>p.marks > 70);

later approach is builder method, in Where function, we are passing lambda expressions.

Lambda expressions are just short cuts of doing things you can always use LINQ queries but if you want to avoid whole query syntax for just applying a simple condition you can just use LINQ builder methods (which asks for lambda expressions) in lambda expressions, you always define some alias and then perform your operation.

As far as => operator is concerned, It works just like assignment operator.
For example:

(p) => p.Gender == “F”
It means  “All persons  p, such that person’s Gender is F”

In some literature this is called “predicate”. Another literature terminology is “Projection”

(p) => p.Gender ? “F” : “Female”
“Each person p becomes string “Female” if Gender is “F”” 

This is projection, it uses ternary operator.
Although i explained with very basic examples but i hope this would help you . . . :)

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