1. What is LINQ
LINQ (pronunciation link) represents language integration query (Language Integrated Query), an extension of the .NEt framework. It allows us to query data collections in SQL query databases. Using it, you can query data from databases, program objects collections, and XML documents.
Here is a simple example that you can query numbers less than 8 in an array and output them.
General steps: Get the data source, create the query, and execute the query. It should be noted that although the query is defined in the statement, it will not be executed until the last foreach statement requests its result.
using System; using ; using ; namespace LINKQuery { class Program { static void Main(string[] args) { int[] number = { 2, 4, 6, 8, 10 }; //Get the data source IEnumerable<int> lowNum = from n in number //Create and store the query, no operation will be performed where n < 8 select n; foreach(var val in lowNum) //Execute query { ("{0} ", val); } (); } } }
2. Query the structure of expressions
A query expression consists of the from clause after the query body, and its clauses must appear in a certain order, and the two parts of the from clause and the select clause are necessary. Let me introduce the sentence first
2.1 from clause
The from clause specifies the data set to be used as a data source, and its syntax is:
from Type Item in Items
Where Type is the type of the element in the collection, it is optional because the compiler can infer the type from the collection. Item is the name of the iterative variable. Items is the name of the collection to be queryed and must be of an enumerable type.
It is similar to foreach, but the foreach statement executes its body when it encounters the code, and the two from clauses do nothing. It creates a background code object that can be executed, which will only be executed if the program's control flow encounters a statement accessing a query variable.
2.2 Join clause
If you are familiar with joins in SQL, joins in LINQ are not difficult for you. If you are not familiar with them, just say nothing.
We can use join to combine data from two or more collections, which accepts two collections and then creates a temporary collection of objects
var query = from s in students join c in course on equals
Equals is used to compare equality fields and cannot be replaced by "==". There are three students and three courses in the following example. What we need to do is to find the names of students who have taken the history courses.
using System; using ; using ; using ; using ; namespace LINKQuery { class Program { public class Student //Declare student class { public int stId; //Student ID public string stuName; //Student name } public class Course //Declare the course class { public int stId; //Student ID public string courseName; //Course Name } static Student[] students = new Student[] { new Student {stId = 1,stuName = "jack"}, new Student {stId = 2,stuName = "taylor"}, new Student {stId = 3,stuName = "fleming"} }; static Course[] courses = new Course[] { new Course{stId = 1,courseName = "art"}, new Course{stId = 2, courseName = "art"}, new Course{stId = 1,courseName = "history"}, new Course{stId = 3, courseName = "history"}, new Course{stId = 3,courseName = "physics"}, }; static void Main(string[] args) { //Check the names of all students who have taken history courses var query = from s in students join c in courses on equals where == "history" select ; foreach(string str in query) { ("{0} ", str); } (); } } }
Output jack fleming
Let’s explain the query process: it will use the objects in student to compare with all objects in course in turn to find out whether they meet the equals where == "history" requirements.
stID | stuName |
1 | jack |
2 | taylor |
3 | fleming |
stID | courseName |
1 | art |
2 | art |
1 | history |
3 | history |
3 | physics |
That is, first match (1, jack) and (1, art), (2, art)...(3, physics) respectively, and then (2, taylor) and (1, art), (2, art)...(3, physics) until all match, you can finally find two matching results.
2.3 let clause
The let clause accepts an operation of an expression and assigns it to an identifier that needs to be used in other operations, which is part of the from...let...where fragment
var query = from a in groupA from b in groupB let sum = a + b where sum < 12 select new(a,b,sum);
2.4 where clause
The where clause removes items that do not meet the requirements based on the subsequent operations. A query expression can have as many where clauses as it is. A term must meet all where conditions to avoid being filtered. The syntax is
where BoolenExpression1 where BoolenExpression2
The previous example has been used where many times, so I won't give an example here
2.5 Orderby clause
Orderby can easily sort the returned data. You can choose from ascending and descending. The default is ascending.
Syntax: orderby Expression ascending or descending
Add an orderby clause to the example in the join clause, and the result returns becomes a fleming jack
var query = from s in students join c in courses on equals where == "history" orderby //Sort select ;
2.6 group clause
The group clause allows you to group the result of the select by the specified key. Each group is distinguished by a field called the key. The group itself is of an enumerable type and can enumerate its items.
var query = from student in students group student by ; foreach (var s in query) { ("{0}", ); foreach (var t in s) { (" {0}", ); } }
2.7 select clause
The select clause specifies which part of the selected object should be selected. You can specify any of the following
a: The entire data item
b: A field of the data item
c: A new object composed of several fields in a data item (or similar to other values)
var query = from s in students select s; //The entire data item var query = from s in students select ; // A field in s var query = from a in groupA from b in groupB let sum = a + b where sum < 12 select new (a, b, sum); //a,b,sumNew fields composed
2.8 Query Continuation: into clause
The query continuation clause can accept part of the structure of the query and give a name so that it can be used in another part of the query.
var someInt = from a in groupA from b in groupB into groupAandB from c in groupAandB select c;
3. Method syntax and query syntax
There are two forms of syntax that can be used when writing queries using LINQ: query syntax and method syntax
a: method syntax: Use standard method calls, these methods are a set of methods called standard query operators
b: query method: It looks very similar to SQL statements and is written in the form of query expressions. Microsoft recommends using query syntax because it is easier to read
At compile time, the CLR converts the query syntax to the method syntax
int[] num = { 2, 4, 6, 8, 10 }; var numQuery = from number in num //Query syntax where number < 8 select number; var numMethod = (x => x < 8); //Method syntax
They get the same result. The where parameters in the method syntax use Lambda expressions
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.