In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is about sample analysis of Lambda expressions in C#. Xiaobian thinks it is quite practical, so share it with everyone for reference. Let's follow Xiaobian and have a look.
In C#syntax there is a more special way to write, called Lambda expression, this expression is written when you query the data directly using the following arrow form to express the query statement: =>. For example, if we want to find all the student data in class number 1001 in the Student List collection, we can use Studentlist.Where(t=>t.ClassCode ='1001 ') statement to do it directly, without writing cumbersome foreach statements or for loops. The Lambda expression operator is =>.
Lambda expression definition
Lambda expression is actually an anonymous function. Lambda expression can contain statements and operations. And can be used to create delegate or expression catalog tree types that support inline expressions with input parameters that can be bound to delegate or expression trees. Lambda expressions can greatly reduce the amount of code, making the code more elegant, concise, and observable.
The expression of Lambda
Expression form: (Input Param)=>Expression. The left side of the expression represents the input parameters, and the right side is the corresponding operation statement or judgment statement, etc., which can include complex methods such as function calls. The operator => is read as goes to, for example the expression t=>t.ClassCode='1001', often goes to ClassCode equal to 1001.
In the above expression, parentheses are optional only if there is only one argument, for example, the following case with two arguments should be written like this
(a,b)=>a==b
When multiple parameters in an expression cannot be typed automatically by the compiler, you need to explicitly specify the type.
(int firstIndex, string str) => str.IndexOf('Hello') > firstIndex
3. The following describes the use of Lambda expressions in the List collection
In C#'s List collection, we often need to use a large number of operations or filtering operations, according to the conventional way is nothing more than using foreach or for to loop the List collection, and finally calculate the result. This method often requires writing multi-line sentences, reading slightly less, of course, complex cases to write time-consuming. Bloggers generally like to be lazy when they encounter this situation. They rarely write loops directly, but use Lambda expressions to complete a statement directly.
Let's assume the format of the example we'll use later:
studentList object: This object is a List collection where the objects in the collection are student entities Student. This collection contains information about the entire school.
ScoreList object: This object is a List collection, the object in the collection is the score entity Score, and this collection stores the score information of students.
Student Entity: This entity contains the following attributes: StudentName, StudentCode, ClassCode, ClassName, BirthDay, Grade. The above English words are relatively simple, do not explain it.
Score Entity: This entity contains the following attributes: StudentCode,SubjectName,ScoreValue. A student may have multiple grades 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');
(2)Query all student entities under the class with class number 1001 and return to list1001 for storage, and arrange them according to the date of birth of the students from small to large.
var list1001=Studentlist.Where(t=>t.ClassCode=='1001').OrderBy(t=>t.BirthDay);
OrderBy is sorted from small to large, and OrderByDescending is used if it needs to be sorted from large to small.
(3)Query all the sets of students with the surname [Li] under the class number 1001, and arrange them according to the date of birth of the students from small to large.
var list=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 with at least one test subject score below 60.
var result = studentList.Where(t => (t.ClassCode == "1001") && (scoreList.Exists(p => p.ScoreValue
< 60 && p.StudentCode == t.StudentCode))); 在上述语句中,lambda表达式中再次嵌入了一个lambda表达式。t参数是studentList中的lambda表达式参数,代表实体为student。p参数为scoreList中的lambda表达式参数,代表的实体为score。 (5)其他较常用的Lambda表达式如下: var a = studentList.FirstOrDefault(t =>t.StudentCode == "10012");//FirstOrDefault returns the first data that matches the condition, null if it does not exist.
var b = studentList.Count(t => t.StudentName == "Li Shimin");//Returns the number of qualified entities
var c = studentList.FindAll(t => t.StudentName.Contains("middle"));//Finds all entity collections with names containing "middle"
var d = studentList.GroupBy(t => t.ClassCode);//Groups 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 scores
var g = scoreList.Average(t => t.ScoreValue);//Average all scores
var h = studentList.Select(t => t.StudentName).Distinct();//Get all student names and remove duplicate names
Lambda expressions are summarized roughly like this, and from the above examples, you can greatly simplify the amount of code and increase readability.
Thank you for reading! About "Lambda expression example analysis in C#" This article is shared here, I hope the above content can be of some help to everyone, so that everyone can learn more knowledge, if you think the article is good, you can share it to let more people see it!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.