Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does => mean in a Linq Expression [duplicate]

Tags:

c#

linq

*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!

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)));
    }
}

Source: Standard deviation of generic list?

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

like image 855
Shaku Avatar asked Oct 04 '13 08:10

Shaku


1 Answers

This notation => means lambda expression

example:

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

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;
}

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.

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:

source: Read about lambda expressions

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

like image 50
Kamil Budziewski Avatar answered Oct 22 '22 10:10

Kamil Budziewski