Home PC Games Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ Lambda expressions of evolution     - How do you prevent other users from accessing your home directory in Linux (Linux)

- Oracle procedure or function Empty Table (Database)

- Nginx load balancing configuration (TCP proxy) (Server)

- installation and configuration of the PHP environment (Apache2) under Linux (Server)

- Memcached and Redis (Linux)

- Linux Shell Scripting multithreading (Programming)

- How to use Linux to download music from Grooveshark (Linux)

- Unsafe reboot start (Linux)

- Java precision four operations (Programming)

- Linux security-related basics (Linux)

- Tab set to four spaces in Vim (Linux)

- Haproxy multi-domain certificate HTTPS (Server)

- Hadoop scheduling availability of workflow platform - Oozie (Server)

- Installing software on Ubuntu: apt-get and dpkg difference (Linux)

- MySQL use the integer type (Database)

- To disable the function by pressing Ctrl-Alt-Del to restart the system in RHEL / CentOS 5/6 (Linux)

- Encounter ORA-00600: internal error code, arguments: [4194] ORA-1552 (Database)

- Bash environment is automatically install and initialize oh-my-zsh & autojump zsh (Linux)

- Build Docker based MongoDB replication cluster environment (Database)

- Linux system on how to use rsync to synchronize data (Server)

  Lambda expressions of evolution
  Add Date : 2018-11-21      

In C # we can customize the commission, but why C # generic delegate built it? Because we often want to use the commission, if the system is built into something you might use the commission, so eliminating the need to define delegates, then delegate instance of step, so that even if the code looks neat and clean, but also improve the program members of the speed of development, why not do! Through this method allows you to review the extension, and can understand the gradual realization of generic delegate system built and commissioned by gradual evolution.


The concept: a packaging method that has five parameters and does not return a value. And the type parameter of the inverter

Here I will implement a custom Action < T> delegate no return value. We also define a Person class, it seems that I always inseparable Person essay topic, ha ha! Consider the following code

    public class Person
        public string Name {get; set;}

        public int Age {get; set;}

        public bool Gender {get; set;}
Then in the console simulation by ForEach method Action delegate, to get a list of definitions of Person GetList ()

        static List < Person> GetList ()
            List < Person> list = new List < Person> () {
            new Person () {Name = "spend one thousand bone (Goddess descendants and the demon god)", Age = 12, Gender = false},
            new Person () {Name = "albino Videos (long stay on the statue)", Age = 13, Gender = true},
            new Person () {Name = "Oriental Yu Qing (iso rotten Gezhu and scholar Shu)", Age = 14, Gender = true},
            new Person () {Name = "light water (long stay disciple)", Age = 15, Gender = false},
            new Person () {Name = "Meng Yuen Long (Shu emperor and long stay disciple)", Age = 16, Gender = true}

            return list;
Because we know that in time by the commission, there are several steps:

(1) define the delegation

(2) Examples of the commission

(3) Add a method pointer to an instance of the delegate object

 But now we do not need to define a delegate, have built trust, you can only be instantiated while adding pointer method is generally a clear method, if we only temporary method, then you can send an anonymous method to play , so the above three steps can be simplified into two steps. Code is as follows:

            var list = GetList ();

            list.ForEach (new Action < Person>
                  delegate (Person p)
                      Console.WriteLine (p.Name);
The code was rather mean JQuery in Each traversal methods.

We know this parameter ForEach method is inside the Action < T> action, so we can be abbreviated as follows

 list.ForEach (delegate (Person p) {Console.WriteLine (p.Name);});
Print results and the above is the same. Its code can continue to be more streamlined, do not worry, we have to be gradual.


The concept: to define a set of conditions and to determine whether the method specified object meets these criteria. Return value bool type, and the type parameter of the inverter.

List of commission than FindAll () method with this generic, and it is from a collection screened out based on a new set of conditions. Section on extension methods just learned, we can customize implement this method with the extension method is applied to the generic collection List to filter according to the parameter condition Predicate delegate.

static List < T> SelfDefineFindAll < T> (this List < T> list, Predicate < T> pre) / * Note: Since it is an extension of the method to add, in this case, in the console Program have declared as static class * /
      List < T> preList = new List < T>; / * Add selected according to the condition data to the collection * /
      foreach (T t in list)
            if (pre (t)) / * according to the conditions to filter * /
                preList.Add (t);

      return preList;
We check out older than 13 years old and according to ForEach to traverse filter out data, the following code:

 var list = GetList ();

 var preList = list.SelfDefineFindAll (delegate (Person p) {return p.Age> 13;});

 preList.ForEach (delegate (Person p) {Console.WriteLine (p.Name);});
Results print out the correct result

Through C # in FindAll, you only need to do the following to achieve the same effect, but not extension methods Bale:

list.FindAll (delegate (Person p) {return p.Name});
In fact, the above code can be more streamlined, do not worry, we step by step, step by step to.


Concept: Representation compare two objects of the same type. Type inverter parameters, return value int.

 list.Sort (new Comparison < Person> (delegate (Person p, Person p1) {return p.Age - p1.Age;})); / * Age ascending order * /
The same can be abbreviated as follows:

 list.Sort ((delegate (Person p, Person p1) {return p.Age - p1.Age;}));

Looks like the system's built-in Func generic delegates are used the most in the actual project development.

The concept: a package having a parameter and returns a value of type TResult method specified parameters. Type inverter parameters, return value parameter type is covariant.

Use the most is the Select List generic collection method of this commission, and look at the built-in method Select how to use Func implementation returns a new collection.

(1) combined with anonymous method implementation

Our next on the basis of the above and then define a class Animal. Property and Person classes, the code is as follows:

    public class Animal
        public string Name {get; set;}

        public int Age {get; set;}

        public bool Gender {get; set;}
Then we passed to the Select method returns a new collection by the collection of Person, namely Animal collection. 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);});
Also print out the results when traversing Person collection time, like seem very complicated, we will streamline the code by the following:

            var list = GetList ();

            List < Animal> animalList = list.Select ((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);});
Here we achieve by extending the method to customize Select () method, as follows:

        public static List < TR> SelfDefineSelect < T, TR> (this List < T> list, Func < T, TR> fun) / * T to pass a generic collection types come in, TR generic collection type returned * /
            List < TR> selList = new List < TR> (); / * generic collection is instantiated to return * /
            foreach (T t in list)
                TR tr = fun (t); / * get passed in a collection of data * /
                selList.Add (tr);
            return selList; / * return the new generic collection * /
 This call is still printed results are correct:

            List < Animal> animalList = list.SelfDefineSelect ((delegate (Person p)
                return new Animal () {Name = p.Name, Age = p.Age, Gender = p.Gender};
            .})) ToList ();
 (2) in conjunction anonymous class to implement

When we use Func when conditions may only need to be converted into a new collection of several examples of members at this time if it is to re-establish a class to get it is overkill, and this time it just needs to pass or membership an anonymous class can be, this is the need to use an anonymous class Func scene. So in view of this, the new collection we will return to the anonymous collection rather Animal collection, transformation of the code as follows:

            var anyousList = list.Select ((delegate (Person p)
                return new {Name = p.Name}; / * Use in conjunction anonymous class * /
By the above system built to achieve generic delegate speaking, it seems a little less than satisfactory, on Delegating too cumbersome code, Microsoft is also clearly know that much of this point, and thus, step by step toward the advanced, it lambda expressions below, this simple structure is simply a. . . Make you cool to the storm.

lambda expressions

 The code can be streamlined said, on how to streamline it? That is, lambda expressions, anonymous methods have been simple enough, but the lambda expression is more concise syntax than anonymous methods! We use lambda expressions to achieve the above-described respectively in Action, Predicate and Func delegate.


            var list = GetList ();

            list.ForEach (d => Console.WriteLine (d.Name);)

            var list = GetList ();

            list.FindAll (d => d.Age> 13);

            list.Select (d => new Person () {Name = d.Name, Age = d.Age, Gender = d.Gender});
            list.Select (d => new {Name = d.Name}); / * lambda expressions anonymous class * /
Well, everything becomes so clear. Since the speed with lambda expressions, knocking code to speed up, my mother no longer have to worry about me stay up late.

Well, the question is, we know lambda lambda expressions into statements and expressions lambda, then what is the difference between the two it? Literally is not a statement lambda is to use braces it? ok, given the code to understand it.

(String str) => {return str.length;} / * statement lambda (have braces and return) * /

(String str) => str.length / * expression lambda (no braces and return, only one formula) * /
The problem again, lambda expressions in the end what is it? We still use decompiler to view list.ForEach (d => Console.WriteLine (d.Age)); the corresponding C # code

 See ForEach () method parameters inside the anonymous method delegates it meant something, and then we go in and see click

We then click Action See

Click on suddenly, and this is not correct that the essence of the method is the anonymous lambda expressions do! So now think about it, the essence of the lambda expression is the essence of the anonymous method, an anonymous method is achieved through the commission. It should be the case.

lambda expressions evolution

We have an extended example of a method to demonstrate the lambda expression is the process of evolution is so vivid.

Suppose the following scenario: find the albino drawn in to spend one thousand bone television, to find the right you win! We get to spend one thousand bone is given a list of all the roles, and then select the albino painting can be.

        / * Find out according to the conditions required to return true you win, lose and vice versa * /

             static bool SelDefine_Extension_IEnumerable < T> (this IEnumerable < T> source, Func < T, bool> func)
                 foreach (var item in source)
                    if (func (item))
                        return true;

                 return false;
Collections list is given below:

            var list = new List < string> () { "spend one thousand bone", "albino painting", "Oriental Yu Qing", "rainbow sky", "sugar treasure", "down eleven", "light water", " Meng Xuan Long "};
Then execute queries in the console extension methods, lambda expressions are listed in this 6-steps:

            list.SelDefine_Extension_IEnumerable (new Func < string, bool> (delegate (string item) {return item.Equals ( "albino Videos");}));
            list.SelDefine_Extension_IEnumerable (delegate (string item) {return item.Equals ( "albino Videos");});

            list.SelDefine_Extension_IEnumerable ((string item) => {return item.Equals ( "albino Videos");});

            list.SelDefine_Extension_IEnumerable ((string item) => item.Equals ( "albino painting"));

            list.SelDefine_Extension_IEnumerable ((item) => item.Equals ( "albino painting"));

            list.SelDefine_Extension_IEnumerable (item => item.Equals ( "albino painting"));
From the beginning of the cumbersome, complex to simple final, each process Microsoft also made some significant efforts, the first point to praise the first! The above with a chart, it is estimated to be more clarity
- Linux smart small switch rfkill (Linux)
- ORA-27054 NFS problem solving (Database)
- Under Linux using Magent + Memcached cache server cluster deployment (Server)
- Use mysqldump backup performed MariaDB (Database)
- Use XtraBackup be physical standby database MySQL (Database)
- Ubuntu 14.10 / Linux Mint 17.1 Win10 compiler install rdesktop 1.8.3 Remote Desktop connection (Linux)
- Nginx reverse proxy and self-signed https (Server)
- Linux centos rm directory does not prompt (Linux)
- Apache Spark1.1.0 deployment and development environment to build (Server)
- Python console achieve progress bar (Programming)
- Java object initialization (Programming)
- CentOS 6.5 install VNC-Server (Linux)
- Build ASP.NET 5 development environment in Ubuntu (Server)
- Linux file time Comments ctime mtime atime (Linux)
- Incremental garbage collection mechanism for Ruby 2.2 (Programming)
- How to install and use the malware detection tool LMD and ClamAV antivirus engine on Linux (Linux)
- Run two MySQL service on one server (Database)
- MySQL bulk insert data script (Database)
- Node.js form --formidable (Programming)
- Ubuntu installed Komodo editor by PPA (Linux)
  CopyRight 2002-2020 newfreesoft.com, All Rights Reserved.