5

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

Community
  • 1
  • 1
Shaku
  • 630
  • 8
  • 19

6 Answers6

8

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?

Community
  • 1
  • 1
Kamil Budziewski
  • 21,193
  • 12
  • 77
  • 95
  • 9
    I can't believe a straight up copy-paste from wikipedia got that many upvotes. Also the question was quite easily Googlable and should be closed – Tony The Lion Oct 04 '13 at 08:45
  • @TonyTheLion 1. It's not wikipedia 2. I was prepairing suitable example, which can be found now in my answer – Kamil Budziewski Oct 04 '13 at 08:51
  • The => operator can be used in two ways in C#: As the lambda operator in a lambda expression, it separates the input variables from the lambda body. In an expression body definition, it separates a member name from the member implementation. – Amit Kumar Verma Mar 09 '18 at 07:13
6

the operator => has nothing to do with linq - it's a lambda expression. It's used to create anonymous functions, so you don't need to create a full function for every small thing.

so the expression:

s => s + 5 

could be translated to:

int fun(int s)
{
return s + 5;
}
elyashiv
  • 3,503
  • 2
  • 26
  • 48
1

=> is the notation for a Lamdba expression, that is basically a shothand way of writing an anonymous method :)

It will also automatically infer types where it can, so that is why v is never declared as an int, but is understood by the compiler to be an int anyway.

Øyvind Bråthen
  • 54,098
  • 26
  • 117
  • 143
  • 4
    this could be a comment not an answer – apomene Oct 04 '13 at 08:46
  • 1
    I think that's harsh. The problem with => is that it's hard to search for if you don't know it's to do with Lambda expressions – guymid Oct 04 '13 at 08:46
  • 1
    There is no other answer to this imo. It's either to link to a page about Lambda expressions, or to copy paste a really big article into here? What would you suggest to do instead to answer this? – Øyvind Bråthen Oct 04 '13 at 08:47
  • Not at all, as it has been answered before. – CodeCaster Oct 04 '13 at 08:48
  • @guymid - What is harsh? I didn't intend to sound harsh at all :) – Øyvind Bråthen Oct 04 '13 at 08:48
  • @ØyvindKnobloch-Bråthen It may be unintended but "You really need to read up on" is implying that OP should already have read up on Lambda... and you don't provide any description of what they are. A brief summary would do. By not including a summary it looks like OP really should know what they are – guymid Oct 04 '13 at 08:50
  • @guymid - It was actually unintended. I have edited it to be nicer now (and also more informative). I even added a extremly friendly smiley in there! Happy? ;) – Øyvind Bråthen Oct 04 '13 at 08:57
  • @ØyvindKnobloch-Bråthen IMHO that's much better :-D – guymid Oct 04 '13 at 08:58
  • @guymid - I aim to please he..he – Øyvind Bråthen Oct 04 '13 at 09:00
1

You can also read this very short article, it is a very good summary of what is a lambda expressions, how to use it and when.

The example given is

List<int> numbers = new List<int>{11,37,52};
List<int> oddNumbers = numbers.where(n => n % 2 == 1).ToList();
//Now oddNumbers is equal to 11 and 37

at line 2, oddNumbers is now equal to numbers where number % 2 is equal to 1, so where number is odd

AlexB
  • 6,664
  • 12
  • 46
  • 66
1

To better understand this. I would rewrite your code without LINQ as below:

public static class Extend
    {
        public static double StandardDeviation(this IEnumerable<double> values)
        {
            double avg = values.Average();
            var newValues = new List<double>();
            foreach (var v in values)
            {
                newValues.Add(Math.Pow(v - avg, 2));
            }

            return Math.Sqrt(newValues.Average());
        }
    }

Now you can compare these two versions of code and see the relation.

Adarsh Kumar
  • 984
  • 6
  • 20
0

This is a lambda expression.

Take a look to this article : http://msdn.microsoft.com/en-us/library/vstudio/bb397687.aspx

Take "v" as an element of the list (so the type is depending of the list), and "=>" indicate the action to do with this element (Math.Pow() is the action).

Xaruth
  • 3,968
  • 3
  • 17
  • 24