=>是什么? Linq表达式中的均值 [英] What does => mean in a Linq Expression

查看:70
本文介绍了=>是什么? Linq表达式中的均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

*尽管这是一个重复的问题,但我之前从未在代码中看到过表达式"=>".如果我知道这是一个特别的lambda表达式,我会用google搜索并自己弄清楚.谢谢!

*Although this is a duplicate question, I had never seen the expression "=>" in code before. If I had known this was specifically a lambda expression, I would have google'd and figured it out on my own. Thanks!

我是使用Linq的新手,所以当我在这段代码中遇到"=>"时,确实让我感到困惑:

I'm new to using Linq, so the use of "=>" really confused me when I ran across it in this code:

using System;
using System.Linq;
using System.Collections.Generic;

public static class Extend
{
    public static double StandardDeviation(this IEnumerable<double> values)
    {
        double avg = values.Average();
        return Math.Sqrt(values.Average(v=>Math.Pow(v-avg,2)));
    }
}

来源:通用列表的标准偏差?

几个问题: =>在这里做什么? Intellisense告诉我'v'是一个整数,但从未声明过.如何运作?

A few questions: What does => do here? Intellisense tells me that 'v' is an int, but it was never declared. How does this work?

推荐答案

此符号=>表示lambda表达式

This notation => means lambda expression

示例:

Enumerable.Range(0,100).Where(x=>x==1);

此处x=> x==1是匿名委托,它接受int作为参数并返回bool.它是:

here x=> x==1 is a anonymous delegate accepting int as a parameter and returning bool. It is:

delegate bool SomeDelegate(int x);

您可以将代表的主体分配给:

and you can assign body of your delegate to:

bool Function(int x)
{ 
   return x==1;
}

lambda表达式是一个匿名函数,可用于 创建委托或表达式树类型.通过使用lambda 表达式,您可以编写可以通过以下方式传递的局部函数 参数或作为函数调用的值返回.拉姆达 表达式对于编写LINQ查询特别有用 表达式.

A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. Lambda expressions are particularly helpful for writing LINQ query expressions.

要创建lambda表达式,请指定输入参数(如果有) 在lambda运算符=>的左侧,您将表达式 或另一侧的语句块.例如,lambda 表达式x => x * x指定一个名为x的参数并返回 x的值的平方.您可以将此表达式分配给委托 类型,如以下示例所示:

To create a lambda expression, you specify input parameters (if any) on the left side of the lambda operator =>, and you put the expression or statement block on the other side. For example, the lambda expression x => x * x specifies a parameter that’s named x and returns the value of x squared. You can assign this expression to a delegate type, as the following example shows:

来源: 了解lambda表达式

这里有一个关于为什么要使用lambda的问题: C#Lambda表达式:为什么要使用它们?

Here is a SO question about why to use lambdas: C# Lambda expressions: Why should I use them?

这篇关于=&gt;是什么? Linq表达式中的均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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