Solved

Linq =>

Posted on 2009-07-07
17
258 Views
Last Modified: 2012-05-07
When we do things like Max in Linq we use => - See attached code example

What does this => actually mean though?
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;
 

namespace LinqExamples

{

    public class Program

    {

        static void Main(string[] args)

        {

            Person dave = new Person { FirstName = "Dave", LastName = "Amour", Age = 42 };

            Person fred = new Person { FirstName = "Fred", LastName = "Smith", Age = 22 };

            Person tiff = new Person { FirstName = "Tiff", LastName = "Bloggs", Age = 24 };

            Person kate = new Person { FirstName = "Kate", LastName = "Brown", Age = 33 };

            Person bill = new Person { FirstName = "Bill", LastName = "Green", Age = 38 };

            Person ian = new Person { FirstName = "Ian", LastName = "Smith", Age = 19 };

            Person fiona = new Person { FirstName = "Fiona", LastName = "Williams", Age = 28 };
 

            Person[] people = new Person[7];
 

            people[0] = dave;

            people[1] = fred;

            people[2] = tiff;

            people[3] = kate;

            people[4] = bill;

            people[5] = ian;

            people[6] = fiona;
 

            Console.WriteLine(people.Max(p => p.Age));
 

            Console.Read();

        }

    }
 

    public class Person

    {

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public int Age { get; set; }

    }

}

Open in new window

0
Comment
Question by:daveamour
  • 8
  • 6
  • 2
  • +1
17 Comments
 
LVL 53

Expert Comment

by:Dhaest
ID: 24792107
=> is a lambda expresison

As you can see, you don't have to explicitly declare a new method to link it with an event. You can use anonymous methods to achieve the same thing in C# 2.0. C# 3.0 introduces an even simpler syntax, lambda expressions, which you write as a parameter list followed by the "=>" token, followed by an expression or a statement block.
http://www.developer.com/net/csharp/article.php/3598381
0
 
LVL 19

Author Comment

by:daveamour
ID: 24792117
Sorry didn't understand any of that in relation my question.
0
 
LVL 18

Expert Comment

by:Richard Lee
ID: 24792124
Max accepts a delegate that takes one parameter. Using the lambda expression is a short way to create and anonymous method (to satisfy the delegate parameter requirements) and pass it to the method Max.
0
 
LVL 53

Expert Comment

by:Dhaest
ID: 24792125
All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block

The lambda expression x => x * x is read "x goes to x times x." This expression can be assigned to a delegate type as follows:

http://msdn.microsoft.com/en-us/library/bb397687.aspx
0
 
LVL 9

Expert Comment

by:Rahul Goel
ID: 24792271
It is like inline statement, using this you no need to create a delagate method for predicate. for example we need to write this way

people.Max(delegate(Person p){
// Do Operations
return p.Age;
});

Now we use inline like this, this is called lambda expression using lambda operator =>
people.Max(p => p.Age);

It saves lines of code, improves the performance, less memory objects

I hope I made clear to u
0
 
LVL 19

Author Comment

by:daveamour
ID: 24792310
Ok so does this sound right for my code example above...
The Max method is available through extension methods defined against the IEnumerable interface,
The Max method takes an argument which is an anonymous method in the form of a lamda expression (which is just a more concise form of writing simple anonymous methods).
Somewhere in the code of the Max method as written by Microsoft  it will push each item in the collection through this anonymous method to figure out which property is used to perform the max calculation.
Within the lamda expression the => is read out as "goes to" - ie p goes to p.Age
Does that sound about right?
0
 
LVL 18

Expert Comment

by:Richard Lee
ID: 24792421
The Max method is an extension method of the IEnumerable interface,

The Max method takes an argument which is a delegate. This parameter can be supplied using a lambda expression which is just a more concise form of writing a simple anonymous methods.

Somewhere in the code of the Max method as written by Microsoft it will push each item in the collection through this method to perform the Max calculation.

When passing the delegate as a parameter to the Max method one of the overloads of the Max extension method will have to be satisfied - this is to say that if you satisfy the delegate which take and integer then the "greater than >"  or "less than <" operator will be used against the integer.

Within the lamda expression the => is read out as "goes to" - ie p goes to p.Age

Is this good?
0
 
LVL 19

Author Comment

by:daveamour
ID: 24792440
Is this good?
I hope so but that was my question!
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 18

Expert Comment

by:Richard Lee
ID: 24792453
I rewrote your question to be a bit more precise and concluding that this is how it works
0
 
LVL 18

Accepted Solution

by:
Richard Lee earned 500 total points
ID: 24792509
I have rewritten the question to be more accurate. I also added a revision for your final example.

---------

The Max method is an extension method of the IEnumerable interface,

The Max method takes an argument which is a delegate. This parameter can be supplied using a lambda expression which is just a more concise form of writing a simple anonymous methods.

Somewhere in the code of the Max method as written by Microsoft it will push each item in the collection through this method to perform the Max calculation.

When passing the delegate as a parameter to the Max method one of the overloads of the Max extension method will have to be satisfied - this is to say that if you satisfy the delegate which take and integer then the "greater than >"  or "less than <" operator will be used against the integer.

Within the lamda expression the => is read out as "goes to"

example:

p => p.Age

or

delegate int del(people p)
{
  return p.Age
}
0
 
LVL 19

Author Comment

by:daveamour
ID: 24792535
Ok thanks that's great and I'll accept that as an answer.
One other question though if you don't mind.
In this link which someone posted, the anonymous delegate does not adhere to the delegate signature of the click event.  How is it we are able to do this?
http://www.developer.com/net/csharp/article.php/3598381
0
 
LVL 19

Author Closing Comment

by:daveamour
ID: 31600495
Thanks
0
 
LVL 19

Author Comment

by:daveamour
ID: 24792626
I'm going to post this last one as a seperate question.
0
 
LVL 18

Expert Comment

by:Richard Lee
ID: 24792633
See the example below; I provide an excerpt

http://www.csharp-station.com/Tutorials/Lesson21.aspx

Using Delegate Parameters with Anonymous Methods

Many event handlers need to use the parameters of the delegate they are based on. The previous example didn't use those parameters, so it was more convenient to not declare them....
0
 
LVL 19

Author Comment

by:daveamour
ID: 24792665
Ok so its built into the compiler that when using anonymous delegates that you don't have to code the method signature if you aren't using the parameters.  If you do code a signature in your anonymous method though then it does have to match the delegate definition.
Am I right in thinking this relaxation only applies to events as I couldn't get the attached code to work.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;
 

namespace LinqExamples

{

    class LambdaTest

    {

        delegate void del(int i);
 

        static void Main()

        {

            del m = delegate() { Console.WriteLine("Hello"); };
 

            m();
 

            Console.Read();

        }

    }

}

Open in new window

0
 
LVL 18

Expert Comment

by:Richard Lee
ID: 24792741
When calling delegates you have to supply the parameter however when constructing anonymous methods you don't have to declare parameter if not used.

See code below:
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;

 

namespace LinqExamples

{

    class LambdaTest

    {

        delegate void del(int i);

 

        static void Main()

        {

            del m = delegate { Console.WriteLine("Hello"); };

 

            m(2);

 

            Console.Read();

        }

    }

}

Open in new window

0
 
LVL 19

Author Comment

by:daveamour
ID: 24792760
Ok right I get it now.
Thanks very much,
 
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now