In the syntax of C #, there is a special writing method called Lambda expression. The writing method of this expression is that when you query data, you directly use the following arrow to represent the query statement: = >. For example, if we want to find all student data with class number 1001 in the student List set, we can use studentlist Where (t = > t.classcode = '1001') statement to complete directly without writing cumbersome foreach statements or for loops. The operator of Lambda expression is = >.
1, Lambda expression definition
Lambda expression is actually an anonymous function. Lambda expression can contain statements, operations and other operations. It can also be used to create a delegate or expression tree type, and supports inline expressions with input parameters that can be bound to the delegate or expression tree. Using lambda expression can greatly reduce the amount of code, making the code more beautiful, concise and observable.
2, Representation of Lambda expressions
Expression form: (input param) = > expression. The left side of the expression represents input parameters, and the right side represents corresponding operation statements or judgment statements, which can include complex methods such as function calls. Operator = > is read as goes to. For example, the following expression t = > t. classcode = '1001', do more goes to ClassCode equal 1001.
In the above expression, parentheses are optional only when there is only one parameter. For example, the following case with two parameters should be written like this
(a,b)=>a==b
When the compiler cannot automatically determine the type of multiple parameters in the expression, you need to specify the type explicitly.
(int firstIndex, string str) => str.IndexOf('Hello') > firstIndex
3, The following describes the use of Lambda expressions in the List set
In C#'s List set, we often need to use a lot of operations such as operation or filtering. According to the conventional way, we just use foreach or for to cycle the List set, and finally calculate the result. This method often needs to write multi line statements, and the readability is slightly poor. Of course, it is time-consuming to write in complex situations. Bloggers in this situation generally prefer to be lazy and rarely write loops directly. Instead, they directly use a statement of Lambda expression.
Let's assume the format of the example we'll use later:
studentList object: this object is a List collection. The objects in the collection are Student entities. This collection holds the information of the whole school students.
scoreList object: this object is a List collection. The object in the collection is the Score entity Score, which stores the Score information for students.
Student entity: this entity contains the following attributes: StudentName, StudentCode, ClassCode, ClassName, BirthDay, Grade. The above English words are relatively simple, so I won't explain them.
Score entity: this entity contains the following attributes: studentcode, subjectname (account name), scorevalue (score, number from 0 to 100). A student may have more than one grade data stored here.
(1) Query all student entities under the class with class number 1001 and return to list1001 for storage
var list1001=Studentlist.Where(t=>t.ClassCode=='1001');//You can also use ToList();
(2) Query all student entities under the class with class number 1001 and return to list1001 for storage, and arrange them from small to large according to the birth date of students.
var list1001=Studentlist.Where(t=>t.ClassCode=='1001').OrderBy(t=>t.BirthDay);//You can also sort OrderByDescending directly without conditions
(3) Query all sets of students with surname [li] under the class with class number 1001, and arrange them from small to large according to the students' birth date.
var list1001=Studentlist.Where(t=>t.ClassCode=='1001'&&t.StudentName.StartWith("Li ")).OrderBy(t=>t.BirthDay);
(4) Find out the class with class number 1001, and there are all students whose scores in at least one examination subject are lower than 60.
var result = studentList.Where(t => (t.ClassCode == "1001") && (scoreList.Exists(p => p.ScoreValue < 60 && p.StudentCode == t.StudentCode)));
In the above statement, a lambda expression is embedded in the lambda expression again. The t parameter is a lambda expression parameter in the studentList, representing that the entity is student. The p parameter is the lambda expression parameter in the scoreList, and the entity represented is score.
(5) Other commonly used Lambda expressions are as follows:
var a = studentList.FirstOrDefault(t => t.StudentCode == "10012");//FirstOrDefault returns the first qualified data, and Null if it does not exist. var b = studentList.Count(t => t.StudentName == "Shi Min Li");//Returns the number of qualified entities var c = studentList.FindAll(t => t.StudentName.Contains("in"));//Find all entity sets with [in] in their names var d = studentList.GroupBy(t => t.ClassCode);//Group the studentList by ClassCode var f = studentList.Max(t => t.BirthDay);//Returns the maximum date of birth. var e = scoreList.Sum(t => t.ScoreValue);//Sum all results var g = scoreList.Average(t => t.ScoreValue);//Average all grades var h = studentList.Select(t => t.StudentName).Distinct();//Get all student names and remove duplicate names