Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Linq =>

Posted on 2009-07-07
17
Medium Priority
?
286 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
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 ITIL
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
 
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 2000 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

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…

609 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