C # Lambda's usage,

Source: Internet
Author: User

C # Lambda's usage,

When I started to get started with the code, I used foreach and for to solve the loop problem. I became a habit and did not want to use other simple methods, lambda can replace loops by chance and is much easier. Of course, it is not easy for me to use lambda, and I don't need to understand the source code because of the usage in many projects in my company. So I simply learned about lambda and summarized it.

1: What is a lambda representation?

Lambda expressions are anonymous functions that can be used to create a delegate or expression directory tree (from MSDN ).

2: I use a picture to represent the composition of lambda.

 

Is like (parameter) =>{ operation}

3: Delegate and lambda usage

First, define three delegates:

Private delegate string dellamate (); // No Parameter
Private delegate void DelLambdaOne (string Param); // A PARAMETER
Private delegate int DelLambdaTwo (int Param1, int param2); // two parameter tables can contain multiple

A: No Parameters

Public static void NoParam () {DelLambda delLambda = () =>{ return "1" ;}; Console. writeLine ("I have no parameter return value: {0}", dellameline ());}

Running result:

B: Only one parameter

Public static void OneParam () {DelLambdaOne delLambdaOne = p => {Console. WriteLine (p) ;}; delLambdaOne ("haha I only have one parameter ");}

Running result:

 

C: more than two parameters

  public static void TwoParam()        {            DelLambdaTwo delLambdaTwo = (p1, p2) =>            {                return p1*p2;            };            Console.WriteLine("{0}*{1}={2}",10,2,delLambdaTwo(10,2));        }

Running result

4: usage of Func AND lambda

In the previous article, the usage of Func is more simplified than that of lamdba. In this case, you do not need to declare the delegate as above (the action and func are similar to not being used for example)

Check the code

Public static void LambdaFunc () {Func <string, string, string> getFunc = (p1, p2) =>{ return p1 + "" + p2 ;}; Console. writeLine (getFunc ("I am the first parameter", "I am the second parameter "));}

Check the result:

5: usage of the combination of linq and lambda (partial)

A: traversal usage

   public string LambdaAndEach()        {            List<int> retList = CreateIisList();            StringBuilder sbBuilder = new StringBuilder();            retList.ForEach(p =>            {                if (p == retList[retList.Count - 1])                {                    sbBuilder.Append("'" + p);                }                else                {                    sbBuilder.Append("'" + p + "',");                }            });            return sbBuilder.ToString();        }

Note 1: CreateIisList () is the method for generating a list.

Check the result:

B: where filtering and searching usage

Public void LambdaAndWhere () {List <User> Users = GetList (); List <int> retList = CreateIisList (); List <int> aaList = new List <int> (); // obtain the List of all user IDs <string> gidList = Users. select (p => p. gid ). toList (); // obtain the aaList = retList of all collections greater than 6. where (p => p> 6 ). toList (); Console. writeLine ("getting all user ID sets {0}", string. join ("", gidList. toArray (); Console. writeLine ("getting all sets greater than 6 {0}", string. join ("", aaList. toArray ()));}
   public List<User> GetList()        {            User User1 = new User() {Gid = Guid.NewGuid().ToString(), UserName = "admin", Pwd = "123456"};            User User2 = new User() { Gid = Guid.NewGuid().ToString(), UserName = "zhangsan", Pwd = "zhangsan" };            User User3 = new User() { Gid = Guid.NewGuid().ToString(), UserName = "lisi", Pwd = "lisi" };            User User4 = new User() { Gid = Guid.NewGuid().ToString(), UserName = "wangwu", Pwd = "wangwu" };            List<User> users = new List<User>();            users.Add(User1);            users.Add(User2);            users.Add(User3);            users.Add(User4);            return users;        }

Check the result:

6: expression directory tree usage

 

This is an operational directory tree and then executed using code.

ParameterExpression a = Expression. parameter (typeof (int), "a"); // create a Parameter in the Expression tree as a node (that is, a in the figure) ParameterExpression B = Expression. parameter (typeof (int), "B"); BinaryExpression AB = Expression. multiply (a, B); // This is the AB node ParameterExpression c = Expression obtained by multiplying a and B in the diagram. parameter (typeof (int), "c"); ParameterExpression d = Expression. parameter (typeof (int), "d"); BinaryExpression cd = Expression. multiply (c, d); BinaryExpression abcd = Expression. multiply (AB, cd); // This is the end node in the current program that is multiplied by AB and cd. // abcd indicates the program to operate, and Expression <Func <int, int, int> lambda = Expression. lambda <Func <int, int> (abcd, a, B, c, d); Console. writeLine (lambda + ""); // compile and generate the delegate Func <int, int> result = lambda. compile (); Console. writeLine (result (2, 2, 2 ));

Running result:

The last one I used is not much because I did not read the summary of the relevant materials. I have not studied it in depth.

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.