What is LINQ?
LINQ (pronounced link) stands for Language Integrated Query)
For details, see LINQ.
Anonymous type
The first member initiator is a value assignment, the second is a member access expression, and the third is a identifier, as shown in the following example:
1 string Sex = "male ";
2 var person = new {Age = 24, SimpleClass. Name, Sex };
3 Console. WriteLine ("{0}, Sex {1}, Age {2}", person. Name, person. Sex, person. Age); remove row numbers
Running result:
Note that the identifier form and access expression must be defined before the anonymous type declaration. Sex is a local variable, and Name is a static field of SimpleClass.
Although the anonymous type is not visible in the Code, the Object Browser can see it. If the compiler encounters another anonymous type with the same parameter name, the same reference type name, and the same sequence, it will reuse this type and directly create a new instance without creating a new anonymous type.
Query syntax and method syntax
Query syntax is declared and looks similar to SQL statements. The query syntax is written using a query expression.
Method syntax is a command, and its usage is a standard method call. A method is a set of methods called standard query operators.
You can also combine the preceding two forms in a query.
The sample code is as follows:
1 var query1 = from n in Enumerable. Range (1, 10)
2 where n <8
3 select n;
4 Console. Write ("query syntax Result :");
5 foreach (var v in query1) Console. Write ("{0} \ t", v );
6
7 var query2 = Enumerable. Range (1, 8). Where (n => n <8 );
8 Console. WriteLine ("");
9 Console. Write ("method syntax Result :");
10 foreach (var v in query2) Console. Write ("{0} \ t", v );
11
12 int count = (from n in Enumerable. Range (1, 10)
13 where n <8
14 select n). Count ();
15 Console. WriteLine ("");
16 Console. WriteLine ("combination of the two methods: {0}", count); running result:
Query expression Structure
1. from clause
The from clause specifies the data set to be used as a data source. It also introduces iteration variables, which represent every element of the data source in sequence.
1 int [] arr = {1, 5, 9, 8, 45, 23, 26, 14, 7, 8, 9 };
2 var query = from n in arr // (n-> iteration variable)
3 where n <10 // use iteration variable
4 select n; // use iteration Variables
5 foreach (var v in query) Console. Write ("{0} \ t", v );
6 Console. WriteLine (""); remove the row number
Running result:
2. join clause
The join clause in LINQ is similar to the join clause in SQL. The join Operation accepts two sets and creates a temporary object set. Each object contains all fields in the original set object, use a connection to combine data in two or more sets.
The sample code is as follows:
1 public class Student
2 {
3 public int StID;
4 public string LastName;
5}
6 public class CourseStudent
7 {
8 public string CourseName;
9 public int StID;
10}
11
12 CourseStudent [] studentInCourses = new CourseStudent [] {
13 new CourseStudent {CourseName = "Art", StID = 1 },
14 new CourseStudent {CourseName = "Art", StID = 3 },
15 new CourseStudent {CourseName = "History", StID = 1 },
16 new CourseStudent {CourseName = "History", StID = 2 },
17 new CourseStudent {CourseName = "Physics", StID = 3}
18 };
19 Student [] students = new Student [] {
20 new Student {StID = 1, LastName = "James "},
21 new Student {StID = 2, LastName = ""},
22 new Student {StID = 3, LastName = ""}
23 };
24
25 // obtain the names of students who take two or more courses
26 var query = (from s in students
27 join c in studentInCourses on s. StID equals c. StID
28 where (from x in studentInCourses where x. StID = c. StID select x. StID). Count ()> 1
29 select s. LastName). Distinct ();
30 foreach (var v in query) Console. Write ("{0} \ t", v );
31 Console. WriteLine ("");
32 // obtain the name of the electives
33 var query1 = from s in students
34 join c in studentInCourses on s. StID equals c. StID
35 where c. CourseName = "History"
36 select s. LastName;
37 foreach (var v in query1) Console. Write ("{0} \ t", v); running result:
Query the from... let... where fragment in the subject
The optional from... let... where section is the first part of the query body. It can be combined by any number of three clauses -- from clause, let clause, and where clause.
1. from clause
The query expression must start with the from clause, followed by the query subject. The subject itself can start with any number of other from clauses. Each from clause specifies an additional data source set merge and introduces the iteration variable to be computed afterwards, the syntax and meaning of all from clauses are the same.
The sample code is as follows:
1 var someInts = from a in Enumerable. Range (1, 5) // The first from clause must be
2 from B in Enumerable. Range (6, 5) // query the first clause of the subject
3 where a <3 & B <10
4 select new {a, B, sum = a + B}; // anonymous type object
5 foreach (var v in someInts) Console. WriteLine (v); remove row number
2. let clause www.2cto.com
The let clause accepts the operation of an expression and assigns it to an identifier that needs to be used in other operations.
The sample code is as follows:
1 var someInts = from a in Enumerable. Range (1, 5)
2 from B in Enumerable. Range (6, 5)
3 let sum = a + B // Save the result in the new variable
4 where sum = 12
5 select new {a, B, sum };
6 foreach (var v in someInts) Console. WriteLine (v); running result:
3. where clause
The where clause removes items that do not meet the specified conditions based on subsequent operations.
The sample code is as follows:
1 var someInts = from a in Enumerable. Range (1, 5)
2 from B in Enumerable. Range (6, 5)
3 let sum = a + B
4 where sum> 12 // condition 1
5 where a = 4 // condition 2
6 select new {a, B, sum };
7 foreach (var v in someInts) Console. WriteLine (v); remove row number
Running result:
Orderby clause
The orderby clause accepts an expression and returns results based on the expression. The default order of the orderby clause is ascending, however, the ascending and descending keywords can be used to show that the Set elements are sorted in ascending or descending order. ordery can have any number of clauses, which must be separated by commas.
The sample code is as follows:
1 var persons = new [] {// an array of anonymous objects
2 new {Name = "Zhang San", Sex = "male", Age = 32, Address = "Guangdong and Shenzhen "},
3 new {Name = "", Sex = "male", Age = 26, Address = "Guangdong Guangzhou "},
4 new {Name = "Wang Wu", Sex = "female", Age = 22, Address = "Guangdong and Shenzhen "},
5 new {Name = "Zhao ", Sex = "male", Age = 33, Address = "Dongguan, Guangdong "}
6 };
7 var query = from p in persons
8 orderby p. Age
9 select p;
10 foreach (var p in query) Console. writeLine ("Name: {0}, Sex: {1}, Age: {2}, Address: {3}", p. name, p. sex, p. age, p. address); running result:
Group by clause
The group clause groups select objects according to some standards. For example, with the array of people in the previous example, the program can group according to their location.
If the group by items are included in the query results, they can be grouped based on the value of a field. The item used as the basis for grouping is called the key. Unlike the select clause, the group clause does not return enumerated types from the original data source, instead, it returns the enumerated type of the groups that have formed the enumerated items. The Group itself is the enumerated type, and they can enumerate the actual items.
The sample code is as follows:
1 var persons = new [] {// an array of anonymous objects
2 new {Name = "Zhang San", Sex = "male", Age = 32, Address = "Guangdong and Shenzhen "},
3 new {Name = "", Sex = "male", Age = 26, Address = "Guangdong Guangzhou "},
4 new {Name = "Wang Wu", Sex = "female", Age = 22, Address = "Guangdong and Shenzhen "},
5 new {Name = "Zhao ", Sex = "male", Age = 33, Address = "Dongguan, Guangdong "}
6 };
7 var query = from p in persons
8 group p by p. Address;
9 foreach (var v in query) // enumeration Group
10 {
11 Console. WriteLine ("{0}", v. Key); // Group Key
12 foreach (var t in v) // enumerate the items in the group
13 {
14 Console. writeLine ("Name: {0}, Sex: {1}, Age: {2}, Address: {3}", t. name, t. sex, t. age, t. address );
15}
16} remove row number
Running result:
Query continuation
The query continuation clause can accept a portion of the query results and assign a name to them so that they can be used in another part of the query.
The sample code is as follows:
1 var somInts = from a in Enumerable. Range (1, 10)
2 join B in Enumerable. Range (5, 10) on a equals B
3 into groupTemp // query continuation
4 from c in groupTemp
5 select c;
6 foreach (var v in somInts) Console. WriteLine (v); the running result is as follows:
Example of using delegate parameters and Lambda
Public static int Count <TSource> (this IEnumerable <TSource> source, Func <TSource, bool> predicate );
The sample code is as follows:
1 IList <int> list = Enumerable. Range (0, 1,100). ToList ();
2 Func <int, bool> myDel = delegate (int x) {return x % 2 = 1 ;}; // delegate the anonymous method
3 var countOdd1 = list. Count (myDel); // call the delegate
4 var countOdd2 = list. Count (x => x % 2 = 1); // Lambda expression
5 Console. WriteLine ("the number of odd numbers obtained by the delegate parameter: {0}", countOdd1 );
6 Console. WriteLine ("Lambda returns an odd number: {0}", countOdd2); Removes the row number
Running result:
From xu_happy_you