LINQ can query a variety of data sources and objects, which can reduce the amount of code and improve retrieval efficiency.
I feel that LINQ is much like SQL. , but the order of the statements is different
The query form for LINQ is as follows:
From ...
Select ...
where ...
For example, query even numbers:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacelinq{classProgram {Static voidMain (string[] args) { //The three Parts of a LINQ Query://1. Data source. int[] numbers =New int[7] {0,1,2,3,4,5,6 }; //2. Query creation. //Numquery is an ienumerable<int> varNumquery = fromNuminchnumberswhere(num%2) ==0 Selectnum; //3. Query execution. foreach(intNuminchnumquery) {Console.Write ("{0}", num); } } }}
Results: 0 2 4 6 Press any key to continue ...
The WHERE statement can use the && | | :
var numquery = from in numbers where20 && (num%4)! =0 select num;
The result is:
2 6 Please press any key to continue ...
var numquery = from in numbers where20| | (num%3) = =0 select num;
The result is:
0 2 3 4 6 Press any key to continue ...
Other keywords in LINQ:
By
var queryLondonCustomers3 = from in customers where" London " by Cust. Name Ascending select Cust;
Use orderby...descending to sort the results in reverse order (Z to A)
Group ... by ...
//Querycustomersbycity is an ienumerable<igrouping<string, customer>> varQuerycustomersbycity = fromCustinchcustomers group Cust by Cust. City; //Customergroup is an igrouping<string, customer> foreach(varCustomergroupinchquerycustomersbycity) {Console.WriteLine (Customergroup.key); foreach(Customer Customerinchcustomergroup) {Console.WriteLine ("{0}", customer. Name); } }
Group ... by ... Group results by a specified key
Join
var innerjoinquery = customers in distributors on Cust. City equals Dist. City Selectnew {CustomerName = cust. Name, Distributorname = Dist. Name};
Join operations create associations between sequences in the data source that do not have an explicit modeling. In LINQ, however, you do not have to use joins as frequently as in SQL , because foreign keys in LINQ are represented in the object model as properties that contain collection of items.
C # Linq