Linqtosql (groupby/having/count/sum/min/max/avg operator)

Source: Internet
Author: User

Group by/having operator

Scenario : grouping data to narrow the scope for us to find data.

Description : An enumerable object that is assigned and returned after a group operation on an incoming parameter. To group or delay

1. Simple form:
G

Statement Description: Use GROUP by to divide the product by CategoryID.

Description: from P in db. Products means that the product objects are taken out of the table. Group p by P.categoryid into G indicates that P is categorized by the CategoryID field. The result is named G, and once renamed, the scope of P is ended, so the last select can only select G. Of course, you do not have to rename it to write:

P.categoryid;

We use the expression:

If you want to traverse all the records in a category, this:

((} } }
2.Select Anonymous class:
{CategoryID = G.key, g};

Description: In this LINQ statement, there are 2 Property:categoryid and G. The essence of this anonymous class is to re-wrap the returned result set. Encapsulates the property of G into a complete grouping. As shown in the following:

If you want to traverse all the records in an anonymous class, do this:

((} } }
3. Maximum Value
{g.key, maxprice = G.max (P = p.unitprice)};

Statement Description: Use GROUP BY and Max to find the highest unit price per CategoryID.

Description: First according to CategoryID classification, judging the price of the largest products in each category. Remove the CategoryID value and assign the UnitPrice value to Maxprice.

4. Minimum value
{g.key, minprice = g.min (P = p.unitprice)};

Statement Description: Use GROUP BY and Min to find the lowest unit price per CategoryID.

Description: First, according to CategoryID classification, judging the lowest unit price of products in each category. Remove the CategoryID value and assign the UnitPrice value to Minprice.

5. Average
{g.key, Averageprice = g.average (P = p.unitprice)};

Statement Description: Use GROUP by and average to get the average unit price per CategoryID.

Description: First by CategoryID classification, remove the CategoryID value and the average price of each product category.

6. Summation
{g.key, totalprice = g.sum (P = p.unitprice)};

Statement Description: Use GROUP BY and sum to get the unit price totals for each CategoryID.

Description: First by CategoryID classification, take out the CategoryID value and the sum of the unit price in each classified product.

7. Counting
{g.key, numproducts = G.count ()};

Statement Description: Use GROUP BY and count to get the number of products in each CategoryID.

Description: First by CategoryID classification, remove the CategoryID value and the number of individual products.

8. With conditional count
{g.key, numproducts = G.count (P = p.discontinued)};

Statement Description: Use GROUP BY and count to get the number of discontinued products per CategoryID.

Description: First by CategoryID classification, remove the CategoryID value and the number of broken goods of each category. In the Count function, a lambda expression is used, and p in the lambda expression represents an element or object in the group, which is a product.

9.Where limit
{g.key, ProductCount = G.count ()};

Statement Description: Based on the product's ―id grouping, the product number is queried for more than 10 of the ID and product quantity. This example uses the WHERE clause after the GROUP BY clause to find all categories with at least 10 products.

Description: A Where condition is nested at the outermost layer when translated into an SQL statement.

10. Multi-column (multiple Columns)
{G.key, g};

Statement Description: Use GROUP by to group products by CategoryID and SupplierID.

Description: Both by product classification, and by supplier classification. After by, new comes out an anonymous class. Here, key is essentially a class object, and key contains two Property:categoryid, SupplierID. With G. Key.categoryid can traverse the value of CategoryID.

11. Expressions (expression)
G

Statement Description: Use GROUP by to return two product sequences. The first sequence contains products with a unit price greater than 10. The second sequence contains products with a unit price less than or equal to 10.

Description: By product unit Price is greater than 10 classification. The results are divided into two categories, greater than the one, less than and equal to another class.

Exists/in/any/all/contains operator

applicable scenario : Used to determine the elements in the set, further narrowing the scope.

Any

Description: Used to determine whether an element in the collection satisfies a condition; (If the condition is NULL, the collection returns true if it is not empty, otherwise false). There are 2 forms, namely the simple form and the conditional form.

1. Simple form:

Only customers who do not have an order are returned:

C

The generated SQL statement is:

(EXISTS[T1]. [CustomerID] = [T0]. [CustomerID]))
2. With conditional form:

Return only the categories that have at least one product that is out of stock:

C

The generated SQL statement is:

WHEREEXISTS([t1].[ CategoryID] = [T0]. [CategoryID]) )
All

Description: Used to determine whether all elements in the set satisfy a certain condition;

1. With conditional form
C

Statement Description: This example returns all orders shipped to customers in their city or customers who have not placed an order.

Contains

Description: Used to determine whether an element is contained in a collection; It is a connection operation to two sequences.

string New String "Arout" "Bolid"    o ) .   ToList ();

Statement Description: Find orders for the three customers "Arout", "Bolid" and "Fissa". An array is defined, using contains in LINQ to SQL, and all the CustomerID are included in the array, that is, all CustomerID are within the set. That is in. You can also place the definition of an array in a LINQ to SQL statement. Like what:

New String "Arout" "Bolid" o).  ToList ();

The not contains is reversed:

New String "Arout" "Bolid" o).  ToList ();
1. Contains an object:
Order= (((  } }

Statement Description: This example uses contain to find which customer contains an order with a OrderID of 10248.

2. Contains multiple values:
string New String "Seattle" "London" "Vancouver" q = db.  Customers.where (p=>cities. Contains (p.city)). ToList ();

Statement Description: This example uses contains to find customers in the City of Seattle, London, Paris or Vancouver.

To summarize this, we have explained the following statement:

Group by/having Group data; delay
Any Used to determine whether an element in a set satisfies a condition;
All Used to determine whether all elements in the collection meet a certain condition;
Contains Used to determine whether an element is contained in a collection;

applicable Scenarios : statistics, such as the number of statistical data, sum, Minimum, maximum, average.

Count

Description : Returns the number of elements in the collection, returns an int type, and no delay. The generated SQL statement is: SELECT COUNT (*) from

1. Simple form:

Get the number of customers in the database:

Q = db. Customers.count ();
2. With conditional form:

Get the number of non-broken products in the database:

Q = db. Products.count (p =!p.discontinued);
LongCount

Description : Returns the number of elements in the collection, returning a long type; For a collection with a large number of elements, the longcount can be used to count the number of elements, which returns a long type and is more accurate. The generated SQL statement is: SELECT COUNT_BIG (*) from

Q = db. Customers.longcount ();
Sum

Description : Returns the sum of the numeric type elements in the collection, which should be of type int, without delay. The generated SQL statement is: SELECT SUM (...) From

1. Simple form:

Get total shipping for all orders:

Q = db. Orders.select (o = o.freight). Sum ();
2. Mapping form:

Get the total number of orders for all products:

Q = db. Products.sum (p = p.unitsonorder);
Min

Description : Returns the minimum value of an element in the collection; The generated SQL statement is: SELECT MIN (...) From

1. Simple form:

Find the lowest unit price for any product:

Q = db. Products.select (p = p.unitprice). Min ();
2. Mapping form:

Find the lowest shipping cost for any order:

Q = db. Orders.min (o = o.freight);
3. Elements:

Find the product with the lowest unit price in each category:

P2};
Max

Description : Returns the maximum value of an element in the collection; The generated SQL statement is: SELECT MAX (...) From

1. Simple form:

Find the most recent hire date for any employee:

Q = db. Employees.select (e = e.hiredate). Max ();
2. Mapping form:

Find the maximum amount of inventory for any product:

Q = db. Products.max (p = p.unitsinstock);
3. Elements:

Find the product with the highest unit price in each category:

P2};
Average

Description : Returns the average of a numeric type element in a collection. The collection should be a collection of numeric types whose return value type is double; The generated SQL statement is: SELECT AVG (...) From

1. Simple form:

Get the average shipping cost for all orders:

Q = db. Orders.select (o = o.freight). Average ();
2. Mapping form:

Get the average unit price for all products:

Q = db. Products.average (p = p.unitprice);
3. Elements:

Find products in each category that have a unit price higher than the average of that category:

P2};

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.