Evolution of lambda expressions

Source: Internet
Author: User

Objective

In C # we can customize delegates, but why does C # have to have generic delegates built into them? Because we often want to use a delegate, if the system built up some of the delegates you might use, then omit the definition of the delegate, and then instantiate the delegate step, so that the code looks concise and clean and can improve the programmer's development speed, he le! This article allows you to review the extension methods, as well as to understand the implementation of the system's built-in generic delegates and the gradual evolution of the delegation.

Action

Concept: Encapsulates a method that has five parameters and does not return a value. And the type parameter is contravariant

Now I'll customize the implementation of a delegate that action<t> no return value . We also define a person class, it seems that my essay will never be inseparable from the topic of person, haha! Please see the following code

     Public class person    {        publicstringgetset;}          Public int Get Set ; }          Public BOOL Get Set ; }    }

Then simulate the action delegate in the console by using the ForEach method, first defining a list of the person to get the getlist ()

StaticList<person>GetList () {List<Person> list =NewList<person>() {             NewPerson () {Name ="Flowers Thousand Bones (nu wa descendants and Demon God)", age = A, Gender =false},            NewPerson () {Name ="white painting (long stay on the statue)", age = -, Gender =true},            NewPerson () {Name ="East Fang (Bachelor of Shu and Master of corruption)", age = -, Gender =true},            NewPerson () {Name ="Light water (long stay Disciple)", age = the, Gender =false},            NewPerson () {Name ="Meng Xuanlang (Emperor Shu and long-stay disciple)", age = -, Gender =true}            }; returnlist; }

Because we know that there are several steps in using the delegate:

(1) Defining a delegate

(2) instantiation of a delegate

(3) Adding a method pointer to the instantiated delegate object

But now we don't need to define a delegate, we have built-in delegate, just instantiate it, and add the pointer to the method is generally a clear method, if we are only a temporary method, then we can send anonymous method to play, so the above three steps can be simplified into two steps. The code is as follows:

            var list = GetList ();            List. ForEach(new action<person>                (                  delegate(person p)                  {                      Console.WriteLine (p.name);                  })                ;

The code above is quite a bit of the meaning of each traversal method in jquery. Results Print out:

We know that the parameter of the Foreach method is action<t> Action , so we can do the following directly

List. ForEach (delegate(person p) {Console.WriteLine (p.name);});

The print results are the same as above. Its code can continue to be more streamlined, not anxious, we gradually come.

predicate

Concept: A method that defines a set of conditions and determines whether the specified object conforms to those conditions. The return value is type bool and the type parameter is contravariant.

Using this generic delegate is the FindAll () method in list, which is to filter out a new set of conditions from a set. The last section just learned the extension method, we can customize the implementation of this method with the extension method on the Generic collection list based on the parameters of the predicate delegate to filter.

Static List<t> selfdefinefindall<t> ( This list<t> List, predicate<t> Pre)/   * Note: Since the extension method is added, in this case the program of the console is also declared as a static class */{      listnew list<t>/* is added to the collection based on the criteria filtered */           foreach inch list)     {            if/* Filter by criteria *                /{prelist.add (t);            }     }       return prelist;}

We query for older than 13 years and iterate through the filtered data based on foreach, with the following code:

var list =var prelist = list. Selfdefinefindall (delegatereturn;}); Prelist.foreach (delegate(person p) {Console.WriteLine (p.name);});

The result prints the correct result, as follows:

by FindAll in C #, you can do the same with just the following, but not the extension method:

List. FindAll (delegatereturn p.name});

The above code can actually be more streamlined, not anxious, we step by step gradually.

Comparison

Concept: Represents a method that compares two objects of the same type. The parameter type is contravariant and the return value is int.

List. Sort (new comparison<person> (delegatereturn p.age-p1. Age; }));  / * age is arranged in order from small to large * /

The same can be abbreviated as:

List. Sort (delegatereturn p.age-p1. Age; }));
Func

It seems that the func is the most used in the actual project development in the system built-in generic delegate.

Concept: Encapsulates a method that has a parameter and returns the type value specified by the TResult parameter. The parameter type is contravariant, and the return value parameter type is covariant.

The most use of this delegate is the select method in the list generic collection, and see how the built-in Select method uses Func to return a new collection.

(1) Combining anonymous method to achieve

We then define a animal class based on the above. As with the person class, the code is as follows:

     Public class Animal    {        publicstringgetset;}          Public int Get Set ; }          Public BOOL Get Set ; }    }

We then return a new collection, the animal collection, through the collection of person through the Select method. The code is as follows:

            var list = GetList ();            List<Animal> animallist = list. Select (new Func<person, animal>(delegate(person p)            {                return New Animal () {Name = p.name, age = p.age, Gender = p.gender};            }). ToList ();            Animallist.foreach (delegate(Animal Animal) {Console.WriteLine (Animal. Name); });

As well as printing out the results when traversing the person collection, it seems cumbersome, and we'll refine the code as follows:

            var list = GetList ();            List<Animal> animallist = list. Select (delegate(person p)            {                returnnew Animal () {Name = p.name, age = P. Age, Gender = p.gender};            }). ToList ();            Animallist.foreach (delegate(Animal Animal) {Console.WriteLine (Animal. Name); });

Let's customize the implementation of the Select () method by extending the method, with the following code:

         Public StaticList<tr> Selfdefineselect<t, Tr> ( ThisList<t> list, func<t, tr>Fun )        /*t is the generic collection type passed in, TR is the generic collection type returned * / {List<TR> sellist =NewList<tr>(); / * Instantiate the returned generic collection *  /foreach(T Tinchlist) {TR TR=Fun (t);            / * Get incoming collection data * /Sellist.add (TR); }            returnsellist; / * Returns a new generic collection * /}

This call is still made, and the result is printed correctly:

            list<animal> animallist = list. Selfdefineselect (delegate(personp)            {                returnnew Animal () {Name = p.name, age = P.age, Gender = P.gender};            }). ToList ();
(2) Combining anonymous classes to achieve

When we use Func to convert to a new collection by a condition, we may need only a few instance members, this time if you also re-establish a class to get a bit of a fuss, this time only need to pass the member to an anonymous class, this is the Func need to use the anonymous class scene. So in view of this, we will return the new collection as an anonymous collection instead of the animal collection, and the code is transformed as follows:

            var anyouslist = list. Select (delegate(person p)            {                return new {Name = P.name};/* Use with anonymous class * /            }));

Through the above-mentioned system built-in generic delegate implementation, it seems a little less satisfactory, about the delegation of the code is too cumbersome, yes, Microsoft is very clear about this, so, step by step toward the advanced, then the lambda expression below, the structure of the simple simply ... Make you feel good.

Lambda expression

The above code said can be streamlined, how to streamline it? That's the lambda expression, the anonymous method is simple enough, but the lambda expression is a more concise syntax than the anonymous method! We use lambda expressions to implement the action, predicate, and Func delegates, respectively.

Action
            var list = GetList ();            List. ForEach (d = Console.WriteLine (d.name);)
predicate
            var list = GetList ();             );
Func
            New Person () {Name = D.name, age = d.age, Gender =
New {Name = d.name}); Anonymous class in/*LAMBDA expression * /

Well, everything has become so clear. Since the lambda expression, the speed of the code has been increased, and my mother never has to worry about me staying up late.

Well, the problem is, we know that lambda expressions are divided into statement lambda and expression Lambda , So what's the difference? Is it literal to understand that the statement lambda is enclosed in curly braces? OK, give the code to understand it.

(stringreturn str.length;}  /* Statement Lambda (with curly braces and return) */ (string str) = str.length  /* expression lambda (no curly braces and return, only one)*/ 

The question is again, what is the lambda expression? We still use anti-compilation to view the list. ForEach (d = Console.WriteLine (D.age)); The corresponding C # code is as follows:

Look at the parameter in the foreach () method is probably the anonymous method delegate, then we click in to see, the code is as follows:

We then click on action to see the following:

, it doesn't mean that the essence of the lambda expression is an anonymous method ! So now think about the nature of the lambda expression as an anonymous method, and the nature of the anonymous method is implemented by the delegate. That's the way it should be.

Lambda-expression Evolution process

Let's demonstrate how vivid the evolution of lambda expressions is with an example of an extension method.

Suppose the following scenario: In the flower thousand bone TV to find the white son draw out, find the right you won! We get a list of all the characters for a flower, and then we can select the white one.

             /*Find what you need by condition, return true you win, and vice versa.*/             Static BOOLSeldefine_extension_ienumerable<t> ( ThisIenumerable<t> Source, Func<t,BOOL>func) {                 foreach(varIteminchsource) {                    if(func (item)) {return true; }                 }                 return false; }

The list of collections is given below:

            varList =Newlist<string> () {"Flowers thousand Bones","The white child draws","Eastern Hongyu Qing","Neon Sky","Sugar Treasure","Fall 11"," Light Water","Meng Xuanlang"};

Then execute the extension method in the console to query, listing the lambda expression 6 :

List. Seldefine_extension_ienumerable (New func<string, Bool> (delegate (string item) {return item. Equals ("White painting"); })); List. Seldefine_extension_ienumerable (delegate (string item) {return item. Equals ("White painting"); }); List. Seldefine_extension_ienumerable (( string Item) = = {return item. Equals ("White painting"); }); List. Seldefine_extension_ienumerable (( string Item) = = Item. Equals ("White painting")); List. Seldefine_extension_ienumerable (Item) = = Item. Equals ("White painting")); List. Seldefine_extension_ienumerable (item = = Item. Equals ("White painting"));

From the beginning of the tedious, complex to the final concise, each process Microsoft is also making a certain effort, first point to praise first! In the light of the above, the estimate will be clearer.

Lambda expression Evolution Six-part

Evolution of lambda expressions

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.