LINQ summation average maximum minimum grouping count and so on

Source: Internet
Author: User

1. Simple form:

var q = from P in db. Products

Group p by P.categoryid into G

Select 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:

var q = from P in db. Products

Group p by P.categoryid;

We use the expression: if you want to traverse all the records in a category, this:

foreach (Var gp in Q)

{

if (GP. Key = = 2)

{

foreach (var item in GP)

{

Do something
}

}

}

2.Select Anonymous class:

var q = from P in db. Products

Group p by P.categoryid into G

Select New

{

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: If you want to traverse all the records in an anonymous class, do this:

foreach (Var gp in Q)

{

if (GP. CategoryID = = 2)

{

foreach (var item in GP.G)

{

Do something

}

}

}

3. Maximum Value

var q = from P in db. Products

Group p by P.categoryid into G

Select New

{

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

var q = from P in db. Products

Group p by P.categoryid into G

Select New

{

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

var q = from P in db. Products

Group p by P.categoryid into G

Select New

{

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

var q = from P in db. Products

Group p by P.categoryid into G

Select New

{

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

var q = from P in db. Products

Group p by P.categoryid into G

Select New

{

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

var q = from P in db. Products

Group p by P.categoryid into G

Select New

{

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

var q = from P in db. Products

Group p by P.categoryid into G

where G.count () >= 10

Select New

{

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)

var categories = from P in db. Products

Group p by New

{

P.categoryid,

P.supplierid

} into G

Select New

{

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)

var categories = from P in db. Products

Group p by New

{

Criterion = p.unitprice > 10

} into G select 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 set satisfies a condition;

No delay. (If the condition is NULL, the collection returns true if it is not empty, otherwise false). There are two forms, namely the simple form and the conditional form.

1. Simple form: Return only customers with no orders:

var q = from C in db. Customers

where!c.orders.any ()

Select C;

The generated SQL statement is:

SELECT [T0]. [CustomerID], [t0]. [CompanyName], [t0]. [ContactName], [t0]. [ContactTitle], [t0]. [Address], [t0]. [City], [t0]. [Region], [t0]. [PostalCode], [t0]. [Country], [t0]. [Phone], [t0].  [Fax] from [dbo].  [Customers] As [T0] WHERE not (EXISTS (SELECT NULL as [EMPTY] from [dbo].[ Orders] as [T1] WHERE [T1]. [CustomerID] = [T0]. [CustomerID]))

2. Conditional form: Returns only the categories that have at least one product out of stock:

var q = from C in db. Categories

where C.products.any (p = p.discontinued)

Select C;

The generated SQL statement is: SELECT [t0]. [CategoryID], [t0]. [CategoryName], [t0]. [Description],[t0]. [Picture] from [dbo]. [Categories] As [T0]where EXISTS (SELECT NULL as [EMPTY] from [dbo].[ Products] as [T1] WHERE ([t1].[ Discontinued] = 1) and ([t1].[ CategoryID] = [T0]. [CategoryID]) )

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

No delay 1. With conditional form

var q = from C in db. Customers

where C.orders.all (o = o.shipcity = = c.city)

Select 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 a set contains an element;

No delay. It is a connection operation to two sequences.

string[] Customerid_set = new string[] {"Arout", "Bolid", "Fissa"};

var q = (from O in db. Orders where Customerid_set.contains (o.customerid) Select 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:

var q = (from O in db. Orders where (new string[] {"Arout", "Bolid", "Fissa"}). Contains (o.customerid) Select O). ToList ();

The not contains is reversed:

var q = (from O in db. Orders where! (New string[] {"Arout", "Bolid", "Fissa"}). Contains (o.customerid) Select O). ToList ();

1. Contains an object:

var order = (from O in db. Orders where O.orderid = = 10248 Select O). First ();

var q = db. Customers.where (P = p.orders.contains (order)). ToList ();

foreach (Var cust in Q)

{

foreach (Var ord in Cust. Orders)

{

Do something

}

}

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

2. Contains multiple values:

string[] Cities = new string[] {"Seattle", "London", "Vancouver", "Paris"};

var 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 packet data;

The delay any is used to determine whether an element in the set satisfies a condition;

No delay of all is used to determine whether all elements in the set satisfy a certain condition;

No delay contains is used to determine whether an element is contained in a set;

Do not delay the application scenario: statistics, such as statistics on the number of data, sum, Minimum, maximum, average.

Count Description: Returns the number of elements in the collection, returning an int type;

No delay. The generated SQL statement is: SELECT COUNT (*) from

1. Simple form:

Get the number of customers in the database: var q = db. Customers.count ();

2. With conditional form:

Get the number of non-broken products in the database: var q = db. Products.count (p =!p.discontinued);

LongCount Description: Returns the number of elements in the collection, returning a long type;

No delay. 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 (*) Fromvar q = db. Customers.longcount ();

Sum description: Returns the sum of the numeric type elements in the collection, and the collection shall be of type int;

No delay. The generated SQL statement is: SELECT SUM (...) From

1. Simple form:

Get total shipping on all orders: var q = db. Orders.select (o = o.freight). Sum ();

2. Mapping form:

Get the total number of orders for all products: var q = db. Products.sum (p = p.unitsonorder);

Min Description: Returns the minimum value of the element in the collection;

No delay. The generated SQL statement is: SELECT MIN (...) From

1. Simple form: Find the lowest unit price for any product: var q = db. Products.select (p = p.unitprice). Min ();

2. Mapping form: Find the lowest shipping cost for any order: var q = db. Orders.min (o = o.freight);

3. Element: Find the product with the lowest unit price in each category:

var categories = from P in db. Products

Group p by P.categoryid into G

Select New

{

CategoryID = G.key,

Cheapestproducts = from P2 in g where P2. UnitPrice = = G.min (P3 = p3. UnitPrice)

Select P2

};

Max Description: Returns the maximum value of the element in the collection;

No delay. The generated SQL statement is: SELECT MAX (...) From

1. Simple form: Find the most recent hire date for any employee: var q = db. Employees.select (e = e.hiredate). Max ();

2. Mapping form: Find the maximum quantity of any product in stock: var q = db. Products.max (p = p.unitsinstock);

3. Element: Find the product with the highest unit price in each category:

var categories = from P in db. Products

Group p by P.categoryid into G

Select New

{

G.key,

Mostexpensiveproducts = from P2 in g where P2. UnitPrice = = G.max (P3 = p3. UnitPrice)

Select P2

};

Average description: Returns the average of the numeric type elements in the collection. The collection should be a collection of numeric types with a return value of type double;

No delay. The generated SQL statement is: SELECT AVG (...) From

1. Simple form: Get the average shipping cost for all orders: var q = db. Orders.select (o = o.freight). Average ();

2. Mapping form: Get the average unit price for all products: var q = db. Products.average (p = p.unitprice);

3. Element: Find the product with the unit price per category higher than the average unit price for that category:

var categories = From p in db. Products

Group p by P.categoryid into G

Select New

{

G.key,

expensiveproducts = From P2 in G where P2. UnitPrice > g.average (p3 = p3. UnitPrice)

Select P2

};

LINQ summation average maximum minimum grouping count and so on

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.