On this page:
1.LINQ part of the query language;
2. Using LINQ method syntax;
3. Sort results orderby words ;
4. aggregate operator;
5. Query complex objects;
6. Projection: create new objects in the query;
7.Distinct()、Any()、All()、First()、FirtOrDefault()、Take()、Skip()运算符;
8. The composition inquiry
9. set operators
10. Joint Join operator
1.LINQ part of the query language
static void Main(string[] args) { string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe", "Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba", "Fatimah" }; var queryResults=from n in names where n.StartsWith("S") select n; Console.WriteLine("Names beginning with S:"); foreach (var item in queryResults) { Console.WriteLine(item); } Console.ReadLine(); }
This example uses a LINQ query syntax for declaring a LINQ query
var queryResults=from n in names where n.StartsWith("S") select n;
The statement includes the following components:
1.1 Statement query result variable var queryResults =;
1.2 specifying a data source from n in names;
1.3 specified condition where n.StartsWith ( "S");
1.4 specify the query element select n;
Note: LINQ is deferred execution, which is performed in actual use, not performed at the time of the statement, the query result variable queryResults just saved a query plan. This embodiment is performed when LINQ query foreach loop.
2. Using LINQ method syntax
There are many ways to use LINQ query, can use LINQ query syntax in the above examples, the syntax may be used LINQ method, also called explicit syntax. LINQ query syntax is the preferred embodiment of the query, because the query syntax is easy to understand, but need to use the method syntax, because some functions can not query LINQ query syntax, such as aggregate operator.
static void Main(string[] args) { string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe", "Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba", "Fatimah" }; var queryResults=names.Where(n=> n.StartsWith("S")); Console.WriteLine("Names beginning with S:"); foreach (var item in queryResults) { Console.WriteLine(item); } Console.ReadLine(); }
Using LINQ method syntax only need to call the corresponding method, this method requires an anonymous method passed as parameters, generally use lamabda create an anonymous method expressions.
3. Sort results orderby clause
You can use orderby clause to sort query results, following the results of the names in alphabetical ascending order
static void Main(string[] args) { string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe", "Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba", "Fatimah" }; var queryResults=from n in names where n.StartsWith("S") orderby n select n; Console.WriteLine("Names beginning with S:"); foreach (var item in queryResults) { Console.WriteLine(item); } Console.ReadLine(); }
orderby clause results may be sorted by any expression, such as the last letter sorted according to names orderby n.Substring (n.Length-1)
orderby default ascending order, in descending order if you want you can add keywords orderby n descending descending
Sort using method syntax
static void Main(string[] args) { string[] names = { "Alonso", "Zheng", "Smith", "Jones", "Smythe", "Small", "Ruiz", "Hsieh", "Jorgenson", "Ilyich", "Singh", "Samba", "Fatimah" }; var queryResults = names.Where(n => n.StartsWith("s")).OrderBy(n => n); Console.WriteLine("Names beginning with S:"); foreach (var item in queryResults) { Console.WriteLine(item); } Console.ReadLine(); }
Sort Descending to the element can be used OrderByDescending
var queryResults = names.Where(n => n.StartsWith("s")).OrderByDescending(n => n.Substring(n.Length-1));
Multi-level sorting
Sometimes required to use multiple fields to sort, such as sales in descending order according to the National ascending, descending city, we need joint use OrderBy \ OrderByDescending and ThenBy / ThenByDescending
var queryResult = customers .OrderByDescending(n=>n.Sales).ThenBy(n=>n.Country).ThenByDescending(n=>n.City);
4. aggregate operator
static void Main(string[] args) { int[] numbers = GenerateLotsOfNumbers(12345678); var queryResults = from n in numbers where n > 1000 select n; Console.WriteLine("Count of numbers >1000:"+queryResults.Count()); Console.WriteLine("Max of numbers >1000:" + queryResults.Max()); Console.WriteLine("Min of numbers >1000:" + QueryResults.Min ()); Console.WriteLine ( " Average Numbers of> 1000: " + queryResults.Average ()); Console.WriteLine ( " the Sum of Numbers> 1000: " + queryResults.Sum (n-=> ( Long ) n-)); // must be converted to a long, because the sum is too large exceeding the range of the int stored Console.ReadLine (); }
Polymerization results in the operator without circulation, in particular a digital type is particularly useful results.
5. query complex object
Simple type of object in the above example is a query numbers, strings, etc., may be used LINQ query complex data type object, etc.
public class Customer { public string ID { get; set; } public string City { get; set; } public string Country { get; set; } public string Region { get; set; } public decimal Sales { get; set; } public override string ToString() { return "ID:" + ID + ",City:" + City + ",Country:" + Country + ",Region:" + Region + ",Sales:"+Sales; } } static void Main(string[] args) { List<Customer> customers = new List<Customer> { new Customer {ID="A" ,City ="New York" ,Country ="USA", Region="North America", Sales =9999}, new Customer {ID="B" ,City ="Munbai" ,Country ="India", Region="Asia", Sales =8888}, new Customer {ID="C" ,City ="Karachi" ,Country ="Pakistan", Region="Asia", Sales =7777}, new Customer {ID="D" ,City ="Delhi" ,Country ="India", Region="Asia", Sales =6666}, new Customer {ID="E" ,City ="S o Paulo" ,Country ="Brazil", Region="South America", Sales =5555}, }; var queryResults = from n in customers where n.Region == "Asia" select n; Console.WriteLine("Customers in Asin:"); foreach (var item in queryResults) Console.WriteLine(item); Console.ReadLine(); }
6. Projection: create new objects in the query
Projection (Projection) to create new data types technical terms from other data types LINQ query, select keywords projection operators
public class Customer { public string ID { get; set; } public string City { get; set; } public string Country { get; set; } public string Region { get; set; } public decimal Sales { get; set; } //public override string ToString() //{ // return "ID:" + ID + ",City:" + City + ",Country:" + Country + ",Region:" + Region + ",Sales:"+Sales; //} } static void Main(string[] args) { List<Customer> customers = new List<Customer> { new Customer {ID="A" ,City ="New York" ,Country ="USA", Region="North America", Sales =9999}, new Customer {ID="B" ,City ="Munbai" ,Country ="India", Region="Asia", Sales =8888}, new Customer {ID="C" ,City ="Karachi" ,Country ="Pakistan", Region="Asia", Sales =7777}, new Customer {ID="D" ,City ="Delhi" ,Country ="India", Region="Asia", Sales =6666}, new Customer {ID="E" ,City ="S o Paulo" ,Country ="Brazil", Region="South America", Sales =5555}, }; var queryResults = from n in customers where n.Region == "Asia" select new { n.Region , n.Country ,n.City ,n.Sales }; Console.WriteLine("Customers in Asin:"); foreach (var item in queryResults) Console.WriteLine(item); Console.ReadLine(); }
Anonymous created without providing the type of projection method ToString again, because the compiler provides a default method again, the way the output object to the name-value pairs (like if you do not override the normal method Tostring output is the class name, such as ConsoleApplication1.Customer)
7.Distinct()、Any()、All()、First()、FirtOrDefault()、Take()、Skip()运算符
Distinct () SQL distinct and unique value as the return data set
var queryResult = customers.Select(n=>n.Region).Distinct(); var queryResult2 = customers.Select(n =>new {n.Country,n.City }).Distinct();
Are Any () to check the data set has any element satisfies a condition, if there are returns true, did not return false; All () to check whether all the elements of the data set are eligible
bool anyUSA = customers.Any(n=>n.Country=="UAS"); var allAsia = customers.All(n=>n.Region =="Asia");
First () returns the data set satisfies the condition of the first element, if the element does not meet the criteria will throw an exception; FirstOrDefault () returns the first element satisfies the condition, and if the difference is not First qualifying element returns empty , no exception is thrown
// query syntax var queryResult = ( from n- in the Customers SELECT n-) .First (n-=> n.Country == " USA " ); // query syntax and grammar mix methods // Method Syntax var customerUSA customers.First = ( = n-> n.Country == " USA " ); var customerAsia customers.FirstOrDefault = (n-=> n.Region == " Asia " );
Take () before removing the N result set, skip () taking the N skipped before the remaining
var salesTop3 = customers.OrderByDescending (n => n.Sales) .Take ( 3 ); var sale left = customers.OrderByDescending (n => n.Sales) .Skip ( 3 );
8. The composition inquiry
Similar compositions query SQL group by, allows data packets, sorted by groups, and the value is compared in the polymerization.
var queryResult = from n in customers group n by n.Region into cg select new { TotalSales = cg.Sum(c => c.Sales), Region = cg.Key }; var orderResult = from cg in queryResult orderby cg.TotalSales descending select cg;
9. set operators
Use set operators, both can quickly result sets. Requirements set operators set members have the same type, in order to obtain the desired result
public class Customer { public string ID { get; set; } public string City { get; set; } public string Country { get; set; } public string Region { get; set; } public decimal Sales { get; set; } public override string ToString() { return "ID:" + ID + ",City:" + City + ",Country:" + Country + ",Region:" + Region + ",Sales:" + Sales; } } public class Order { public string ID { get; set; } public decimal Amount { get; set; } }
List<Customer> customers = new List<Customer> { new Customer {ID="A" ,City ="New York" ,Country ="USA", Region="North America", Sales =9999}, new Customer {ID="B" ,City ="Munbai" ,Country ="India", Region="Asia", Sales =8888}, new Customer {ID="C" ,City ="Karachi" ,Country ="Pakistan", Region="Asia", Sales =7777}, new Customer {ID="D" ,City ="Delhi" ,Country ="India", Region="Asia", Sales =6666}, new Customer {ID="E" ,City ="S o Paulo" ,Country ="Brazil", Region="South America", Sales =5555}, }; List<Order> orders = new List<Order> { new Order {ID ="A",Amount=100}, new Order {ID ="B",Amount=200}, new Order {ID ="F",Amount=300}, }; var CustomerIDs = from n- in the Customers SELECT n.ID; var OrderIDs = from n- in Orders SELECT n.ID; // with a customer order ID var customerWithOrders = CustomerIDs .Intersect (OrderIDs); // no customer orders var ordersNoCustomers = orderIds.Except (CustomerIDs); // customer and order ID set var allCustomersOrdersIds = customerIds.Union (OrderIDs);
10. Joint Join operator
Join Join operator similar to the SQL operation, the two data sets can be connected by a key field.
var queryResult = from n in customers join o in orders on n.ID equals o.ID select new { n.ID ,n.City ,SaleBefore=n.Sales ,OrderAmount=o.Amount ,SaleAfter=n.Sales +o.Amount };