Lambda expressions and Query expressions (1) Basic Concepts

Source: Internet
Author: User

Lambda expressions are also an anonymous function, which is more concise than anonymous functions. It can contain expressions and statements and is suitable for creating delegates and events.

Query expression: it is an expression expressed by the query syntax. It can retrieve data from one or more given data sources and define the expression of the search result.

Lambda expression: it consists of input parameters, Lambda operators, and expressions (or statement blocks.

Its syntax is as follows:

(input parameters) => empression;  : input parameters : 表示输入参数,它是可选的;    : “=>”  为Lambda运算符(读作goes to);  : empression : 表示表达式或语句块。

[Example 1-1]

m => m * m; 

Analysis: lambda expressions calculate the square of the given Parameter m and return the calculation result.

[Example 1-2] and obtain the value of this expression.

int n = (int m) => m * m;   

Analysis: lambda expressions calculate the square of the given input parameter m and return the calculation result. The result is saved as N variable.

 

1. input parameters:

In a Lambda expression, the input parameter is the left part of the lambda operator. It can contain 0, 1, or more parameters.

When the input parameter is 1, a pair of small arc on the left side of the lambda expression can be omitted.

When the number of parameters is greater than or equal to 2, multiple parameters in a pair of small arc on the left of the lambda expression are separated by commas.

[Example 1-3] The number of input parameters is 0.

() => Console.WritleLine("This is a Lambda empression.");

Analysis: because the number of input parameters of the preceding Lambda expression is 0, a pair of small arc on the left of the lambda expression cannot be ignored.

[Example 1-4] its input parameter contains a parameter: M. This expression calculates the product of M parameter and 2.

m => m * 2;

Analysis: the input parameters of the above Lambda expression omit a small pair of arc, which is equivalent to the "(m) => M * 2;" Lambda expression.

[Example 1-5] its input parameters include M and N. This expression calculates the product of M and N parameters.

(m,n) => m * n; 

Expression or statement block:

Lambda statement block: composed of multiple lambda expressions.

The statement block is placed on the right of the operator and serves as the body of Lambda. Depending on the subject, lambda expressions can be divided into expressions Lambda and statements lambda.

Statement blocks can contain multiple statements, including loops, method calls, And if statements.

[Example 1-6] the right part is an expression. This expression calculates the Square Value of the M parameter.

m => m * m; 

If the right part of the lambda expression is a statement block, the block must be surrounded by "{" and.
[Example 1-7] its input parameters include M and N. The right side of the expression contains two expressions:

The first expression calculates the product of the M and N parameters, and the result is saved as the result variable;

The second expression displays the value of the result variable.

(m,n) => { int result = m * n; Console.WritleLine(result); } 

Analysis: the right part of the lambda expression contains two expressions. Therefore, the right part of the expression must be surrounded by "{" and.

 

Query expression:

Query expression: it is an expression expressed by the query syntax. It is used to query and convert data from any data source that supports LINQ.

Query expression: it is constructed using many common C # languages and is easy to read and understand. It consists of a group of clauses written in declarative syntax similar to SQL or XQuery.

Each clause can contain one or more C # expressions. These C # expressions may also be Query expressions or contain Query expressions.

Query expression: it must start with the from clause and end with the select or group clause. Between the first from clause and the last select clause or group clause,

It can contain one or more where clauses, let clauses, join clauses, orderby clauses, and group clauses,

But the from clause. It includes eight basic clauses, which are described as follows.
From clause: Specifies the data source and range variable of the query operation.
Select clause: specifies the type and format of the query result.
Where clause: Specifies the logical conditions for filtering elements.
Let clause: introduces the range variable used to temporarily Save the results of the subexpression in the query expression.
Orderby clause: sorts query results in ascending or descending order.
Group clause: groups query results.
Into clause: provides a temporary identifier. The join clause, group clause, or select clause can reference the intermediate results in the query operation using this identifier.
Join clause: connects multiple data sources used for query operations.

[Example 1-8] This query expression queries every element in the ARR array.

int[] arr = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var query1 = from n in arr   select n; 

[Example 1-9] This query expression is used to query elements larger than 6 in the ARR array.

int[] arr = new int[]{0,1,2,3,4,5,6,7,8,9};var query2 = from n in arr  where n > 6 select n; 

Note: The query1 in Example 1-8 or the query2 variable in Example 1-9 only saves the query operation, not the query result.

When a query expression performs a query operation, the query expression results are calculated. The query1 and query2 variables belong to the set type.

 

From clause:

The from clause is used to specify the data source and range variables of the query expression. It is an essential part of the query expression and appears at the beginning.

Data source: not only the data source of the query itself, but also the data source of the subquery. Range variables are used to represent each element in the data source sequence.

Note: The data source type specified by the from clause must be ienumerable, ienumerable <t>, or a derived type.

[Example 1-10] This query expression queries every element in the ARR array.

In the query expression, the ARR array is the data source, and N is the range variable. The type of the N range variable is the element type of the ARR data source.

int[] arr = new int[]{0,1,2,3,4,5,6,7,8,9};var query = from n in arr  select n;       

Next we will learn the data source and the Query expressions that contain different from clauses:

1. Specify the data source from the data source,

It can be in the form of static array, dynamic array (arraylist), set, dataset, data table, MML fragment, MML file, etc.

If the data source implements the ienumerable <t> interface, the compiler can infer that the type of the range variable is its element type.

For example, if the data source type is ienumerable <userinfo>, You can infer that the range variable type is userinfo.

[Example 1-11] Create a query expression.

This query expression queries every element in the list generic array. List Generic Array is the data source, and U is the range variable. The U range variable type is the List Data Source Element type (userinfo ).

List<UserInfo> list = …       //其初始化代码已经省略 var query = from u in list    //查询list泛型列表中的每一个元素                          select u; 

If the data source is not of the generic ienumerable type (such as arraylist), you must explicitly specify the type of the range variable.

 

[Example 1-12] query each element in the list array. List array is the data source, and U is the range variable. The type of the U-range variable is specified as the element type (userinfo) of the List data source ).

ArrayList list = new ArrayList();list.Add(…);                                         //添加UserInfo类的实例,代码已经省略 …                                     //其初始化代码已经省略 var query = from UserInfo u in list        //查询list泛型列表中的每一个元素              select u;

2. query expression containing a single from clause

In a query expression, at least one from clause exists. When there is only one from clause, the query expression is called a query expression that contains a single from clause.

Generally, a query expression containing a single from clause only contains one data source.

[Example 1-13] This query expression queries every element in the ARR array. It is a query expression containing a single from clause.

int[] arr = new int[]{0,1,2,3,4,5,6,7,8,9}; var query = from n in arr                           select n; //创建一个查询表达式query

3. A query expression that contains multiple from clauses. When two or more from Clauses exist, the query expression is called a query expression that contains multiple from clauses.

[Example 1-14] the query expression contains two from clauses.

They query two independent data sources: arr1 array and arr2 array. Finally, use the select clause to calculate the sum of the current element.

int[] arr1 = new int[]{0,1,2,3,4,5,6,7,8,9};int[] arr2 = new int[]{0,1,2,3,4,5,6,7,8,9}; var query = from a in arr1   from b in arr2   select a + b;    //包含多个from子句的查询表达式

4. query expression containing the composite from clause
In a query expression, each element in the data source of the query expression may also serve as the data source of the query expression.

To query the elements in each element of the data source, you must use the composite from clause. A composite from clause is similar to a nested foreach statement.

[Example 1-15] create a class named test below,

This class contains two fields: Name and aliasname.

The type of the Name field is string,

The aliasname field belongs to the string type list. Therefore, it can also be used as a data source for subquery expressions.

public class Test         {               public string Name;  //名称               public List<string> AliasName;       //别名列表        }

[Example 1-16] Create a query expression. The query expression contains a composite from clause:

The first from clause queries the list generic set;

The second from clause queries the aliasname field of the element in the list set, which is the subquery of the first from clause.

Finally, use the select clause to concatenate the value of the name attribute of the U variable and the value of the name variable into a string.

List<MUserInfo> list = …                //其初始化代码已经省略 var query = from u in list              //查询list泛型列表                          from name in u.AliasName   //查询每一个元素的AliasName属性的值                           select u.Name + name;

Select clause:

The Select clause is used to specify the type of values that will be generated during query execution. The query expression must end with the select clause or group clause.
[Example 1-17] This query expression queries each element in the ARR array.

int[] arr = new int[]{0,1,2,3,4,5,6,7,8,9};var query = from n in arr            select n;

[Example 1-18] the query expression queries the product of each element and 10 in the ARR array.

int[] arr = new int[]{0,1,2,3,4,5,6,7,8,9}; var query = from n in arr select n * 10;

Analysis: the "N * 10" expression in the select clause determines the expression of the query result, that is, the product of each element and 10.

[Example 1-19] This query expression queries each element in the ARR array. The query result is a collection of objects.

This object contains two attributes: ID and name, which are created by the anonymous object initializer in the select clause.

The value of the ID attribute of each object is the value of the current element, and the value of the name attribute is a string representation of the value of the element.

int[] arr = new int[]{0,1,2,3,4,5,6,7,8,9}; var query = from n in arr                          select new { ID = n, Name = n.ToString()    };                         

Analysis: "New {id = N, name = n. tostring ()}" is an anonymous object initialization, which creates an anonymous object.

Where clause:

Used to explain which elements in the data source will be returned in the query expression. It applies a Boolean condition to each element in the data source and returns the element of the specified condition.

A query expression can contain one or more where clauses.

[Example 1-20] This query expression queries elements less than 3 from the ARR array.

int[] arr = new int[]{0,1,2,3,4,5,6,7,8,9}; var query = from n in arr   where n < 3    select n;

Analysis: The WHERE clause contains only one Boolean expression "n <3", which filters elements smaller than 3.

A Where clause can also contain multiple boolean expressions. Each expression is directly separated by a logical operator (such as & and |.
[Example 1-21] This query expression queries elements greater than 3 and less than 6 from the ARR array.

int[] arr = new int[]{0,1,2,3,4,5,6,7,8,9};var query = from n in arr            where n > 3 && n < 6            select n;

Analysis: The WHERE clause contains two boolean expressions "n> 3" and "n <6", which specify that elements greater than 3 and less than 6 are filtered. The two boolean expressions are connected using the & operator to calculate the logical and.
A Where clause can not only contain a Boolean expression, but also a method that returns a Boolean value.

[Example 1-22] This query expression queries an even number of elements from the ARR array.

int[] arr = new int[]{0,1,2,3,4,5,6,7,8,9}; private bool IsEven(int i) //判断i参数是否为偶数.如果是,则返回true,否则返回false {  return i % 2 == 0 ? true : false; } var query = from n in arr   where IsEven(n)  select n;

Analysis: The WHERE clause contains a method "iseven (INT I)" that returns a Boolean value )". This method is used to determine whether the element is an even number. If yes, true is returned; otherwise, false is returned.

Let clause:

The let clause is used to create a new range variable. It is used to store the results of a subexpression.

The let clause initializes the variable using the result of the expression provided by the programmer. Once the value of this range variable is initialized, it cannot be used to store other values.

[Example 18-23] This query expression queries an even number of elements from the ARR array.

int[] arr = new int[]{0,1,2,3,4,5,6,7,8,9};var query = from n in arr  let isEven = return n % 2 == 0 ? true : false   //判断n元素是否为偶数。            where isEven  
select n;

Analysis:

"Return n % 2 = 0? True: false "expression determines whether the N element is an even number. If yes, true is returned; otherwise, false is returned.

"Let iseven = return n % 2 = 0? True: false "expression creates a new range variable iseven using the let clause to save" Return n % 2 = 0? True: false.

The where iseven expression uses the WHERE clause to filter elements whose iseven value is true.

 

Orderby clause:

The orderby clause can sort the returned query results in ascending or descending order. The Ascending Order is specified by the keyword ascending, And the descending order is specified by the keyword descending.
Note: The orderby clause is sorted in ascending order by default.

[Example 1-24] the query expression queries the elements greater than 1 and less than 6 from the ARR array, and sorts the query results in descending order according to the nelements.

int[] arr = new int[]{0,1,2,3,4,5,6,7,8,9}; var query = from n in arr where n > 1 && n < 6 orderby n descending select n;      

// Create a query expression. The query orderby clause can contain one or more sort expressions separated by commas.

[Example 1-25]

This query expression queries elements greater than 1 and less than 6 from the ARR array. It uses the orderby clause to sort the query results and contains two sort keywords,

The details are as follows.

N % 2: sort in ascending order; N: sort in descending order. ?

Note: the priority of the N % 2 sorting keyword is greater than that of the N sorting keyword.

Therefore, the results of the query expression are first sorted by the N % 2 sort keyword in ascending order, and then by the N sort keyword in descending order.

Analysis: In the "orderby n % 2 ascending, N descending" expression, the "ASCENDING" after the first sorting keyword can be omitted. The default sorting method is ascending.

 

Group clause:

The Group clause is used to group query results and return an object sequence. These objects contain zero or more items that match the key value of the reorganization. You can also use the group clause to end the query expression.
Note: Each group is not a single element, but a sequence (also a set ).

[Example 1-26] the query expression queries elements greater than 1 and less than 6 from the ARR array, and groups the query results according to the value of the N % 2 expression.

int[] arr = new int[]{0,1,2,3,4,5,6,7,8,9}; var query = from n in arr    where n > 1 && n < 6    group n by n % 2;   

Analysis:

The query expression is a sequence (type: ienumerable <igrouping <int, int> ),

The element type of the sequence is igrouping <int, int>. In fact, the element in the query result is also a sequence.

[Example 1-27] the following two foreach statements are used to display the values of each element in the query expression results.

foreach(var g in query)        //查询query中的元素,该元素也是一个序列,类型为IGrouping<int,int> {       foreach(var o in g)         //查询每一个分组中的元素,该元素的类型int         {                 Console.WriteLine(o); //显示元素的值         }} ?

Note: After grouping query results using the group clause, each group has a key (represented by the key attribute ).

You can use the key attribute to obtain the key values of each group.

 

Into clause:

The into clause can be used to create a temporary identifier to store the results of a group, join, or select clause to this identifier.

[Example 18-29] the query expression queries elements greater than 1 and less than 6 from the ARR array and groups the query results according to the value of the N % 2 expression.

The query expression is described as follows.

where n > 1 && n < 6:     指定筛选大于1且小于6的元素。 group n by n % 2 into g:  按照n % 2表达式的值对查询结果进行分组,并使用into子句创建临时标识符g。该临时标识符临时保存分组结果。 
from sn in g: 从g标识符指定的每一个分组中查询sn元素。 select sn: 表示查询sn元素。 int[] arr = new int[]{0,1,2,3,4,5,6,7,8,9}; var query = from n in arr where n > 1 && n < 6 group n by n % 2 into g from sn in g select sn;

// Create a query expression for query analysis: the query results of the preceding query expression include four elements, which are 2, 4, 3, and 5 in sequence.

Join clause:The join clause is used to join two data sources, that is, to set the relationship between the two data sources.

Three Common connection methods.
Internal join: similar to the inner join clause in an SQL statement.
Group join: A join clause that contains the into clause.
Left Outer Join: similar to the left join clause in an SQL statement.

1. Internal join:The internal join clause requires that both data sources have the same value, that is, both data sources must have elements that meet the join relationship.

[Example 1-30] the query expression joins the ARRA and arrb Arrays Using the join clause,

The details are as follows.

创建arra数组,它包含10个元素(0~9)。 创建arrb数组,它包含5个元素(0、2、4、6和8)。 创建query查询from a in arra:   从arra数组中选择元素,并表示为a。where a < 7:      从arra数组中选择小于7的元素。 join b in arrb on a equals b:将arra和arrb数组进行联接,同时满足a和b相等的条件。其中,b元素是arrb数组中的元素。 select a:选择a元素。int[] arra = new int[]{0,1,2,3,4,5,6,7,8,9};int[] arrb = new int[]{0,2,4,6,8}; var query = from a in arra where a < 7  join b in arrb on a equals b select a;  

Analysis: The above query expression first selects elements smaller than 7 (including 0 ~ 6), then join the arrb array, and obtain the elements contained in the {, 6} set and included in the arrb array. Finally, the query expression results contain four elements (0, 2, 4, and 6 ).

2. Group join:The join clause Group joins join clauses that contain the into clause. It matches the elements of the left and right data sources in sequence. All elements of the Left data source appear in the query results. If a match is found in the right data source, the matched data is used. Otherwise, it is expressed as null.
[Example 1-31] Create a query expression. The query expression uses the join clause to join ARRA and arrb arrays,

The details are as follows:

创建arra数组,它包含10个元素(0~9)。创建arrb数组,它包含5个元素(0、2、4、6和8)。创建query查询。from a in arra:   从arra数组中选择元素,并表示为a。where a < 7:      从arra数组中选择小于7的元素。 join b in arrb on a equals b into g:将arra和arrb数组进行联接,同时满足a和b相等的条件。最后,保存为g分组。其中,b元素是arrb数组中的元素。select new{ID = a, Values = g}:

The specified query result is a collection of objects. It contains two attributes: ID and values, which are created by the anonymous object initiator in the select clause. The value of the ID attribute of each object is the value of the current element, and the value of the value attribute is G group.

Analysis: The above query expression first selects elements smaller than 7 (including 0 ~ 6), and then join the arrb array. Finally, the query expression results contain seven elements,

The details are as follows.

1st elements: the value of the ID attribute is 0, and the value of the values attribute is a set, which contains only one element 0.

2nd elements: the value of the ID attribute is 1, and the value of the values attribute is an empty set.

3rd elements: the value of the ID attribute is 2, and the value of the values attribute is a set, which contains only one element 2.

4th elements: the value of the ID attribute is 3, and the value of the values attribute is an empty set.

5th elements: the value of the ID attribute is 4, and the value of the values attribute is a set, which contains only one element 4.

6th elements: the value of the ID attribute is 5, and the value of the values attribute is an empty set. 7th elements: the ID attribute value is 6,

The value of the values attribute is a set that contains only one element 6.

 

3. left Outer Join: The left Outer Join of the join clause returns all the elements in the left data source sequence, even if they do not have matching elements in the right sequence.
[Example 1-32] the query expression uses the join clause to join the ARRA and arrb arrays,

The details are as follows.

创建arra数组,它包含10个元素(0~9)。创建arrb数组,它包含5个元素(0、2、4、6和8)。创建query查询。from a in arra:  从arra数组中选择元素,并表示为a。where a < 7:     从arra数组中选择小于7的元素。 join b in arrb on a equals b into g: 将arra和arrb数组进行联接,同时满足a和b相等的条件。最后,保存为g分组。其中,b元素是arrb数组中的元素。
select ab: 选择ab元素。

The left data source is the data source generated by "from a in ARRA" and "where a <7,

The right data source is an array of arrb.

From AB in G. defaultifempty (): queries each element in the G group. If no element exists in the group, the default value is returned. ?

Note: If the sequence (G here) is null, The defaultifempty () method returns a sequence containing only one element. The value of this element type is the default value (0 here ).

Select AB: select the AB element.

Analysis: The preceding query expression

First, select the element smaller than 7 (including 0 ~ 6), and then left join with the arrb array. The query expression contains seven elements (equal to the number of elements in the left data source ).

If the G group is empty, the default value (0) of the element type of the group is returned. Otherwise, the element is returned.

When the values of elements in the left data source are 1, 3, and 5, the G group is empty. In this case, the default value 0 is returned.

When the values of elements in the left data source are 0, 2, 4, and 6, the G group is not empty. In this case, it returns the values of this element, which are 0, 2, 4, and 6.

Finally, the query expression results contain 7 elements (0, 0, 2, 0, 4, 0, and 6 ).

 

Lambda expressions and Query expressions (1) Basic Concepts

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.