classProgram {Static voidMain (string[] args) {List<Person> persons =NewList<person>() { NewPerson{id=101, name="lin1"}, NewPerson{id=102, name="lin2"}, NewPerson{id=103, name="lin3"} }; Person Person=persons. Find (Delegate(Person P)//This was an anonymous method. { returnP.id = =101; } ); Person P1= persons. Find (p=>p.id==101);//using lambda expressionperson P2 = persons. Find (person P) =>p.id==101);//You can also explicitly the input type but no requiredConsole.WriteLine ("Person Id={0},name={1}", person.id, person. Name); } } classPerson { Public intID {Get;Set; } Public stringName {Get;Set; } }View Code
= = called Lambda operator and read as Goes to. Notice A lambda expression you don ' t has to use the delegate keyword explicitly and don ' t has to specify the I Nput parameter type explicity. The parameter type is inferred (torn out). Lambda expressions is more convenient to use than anonymous methods. Lambda expressions is particularly helpful for writing LINQ query expressions.
In the most of the cases lambda expressions supersedes (alternative) anonymous methods. To my knowlege, the only time I prefer to use anonymous methods over Lambdas are, when we had to omit (omitted) the parameter Li St when it's not used within the body.
Anonymous methods allow the parameter list to being omitted entirely when it's not used within the body,where as with Lambda Expressions this isn't the case.
For example, with anonymous method notice. We have omitted the parameter list as we is not using them within the body
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 would get a compilar error.
Part of the LAMBDA expression in C #