Part 99 Lambda expression in c #,

Source: Internet
Author: User

Part 99 Lambda expression in c #,
Class Program {static void Main (string [] args) {List <Person> persons = new List <Person> () {new Person {ID = 101, name = "lin1"}, new Person {ID = 102, Name = "lin2"}, new Person {ID = 103, Name = "lin3 "}}; person person = persons. find (delegate (Person p) // this is an anonymous method. {return p. ID = 101;}); Person p1 = persons. find (p => p. ID = 101); // using lambda expression Person p2 = persons. find (Person p) => p. ID = 101); // you can also explicitly the input type but no required Console. writeLine ("person id = {0}, name = {1}", person. ID, person. name) ;}} class Person {public int ID {get; set;} public string Name {get; set ;}}View Code

=> Is called lambda operator and read as Goes. notice that with a lambda expression you don't have to use the delegate keyword explicitly and don't have to specify the input parameter type explicity. the parameter type is inferred (pushed out ). lambda expressions are more convenient to use than anonymous methods. lambda expressions are special helpful for writing LINQ query expressions.

In most of the cases lambda expressions supersedes (alternative) anonymous methods. to my knowlege, the only time I prefer to use anonymous methods over lambdas is, when we have to omit (Omitted) the parameter list when it's not used within the body.

Anonymous methods allow the parameter list to be omitted entirely when it's not used within the body, where as with lambda expressions this is not the case.

For example, with anonymous method notice that we have omitted the parameter list as we are not using them within the body

Button.Click += delegate{MessageBox.Show("hello world.");};

The above code can be rewritten using lambda expression as shown below. Notice that with lambda we cannot omit the parameter list.

Button.Click+=(sender,e)=>{MessegeBox.Show("hello world.");};Button.Click+=()=>{MessegeBox.Show("hello world.");};//if omit parameter list it will get a compilar error.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.