Group by/having and exists/In/any/all/contains

Source: Internet
Author: User
ArticleDirectory
    • Group by/having Operator
    • Exists/In/any/all/contains operator
    • Any
    • All
    • Contains

We will continue to explain the LINQ to SQL statements. In this article, we will discuss the Group by/having operators and the exists/In/any/all/contains operators.

Group by/having Operator

Applicable scenarios: Grouping data. narrow down the scope of data for us.

Description: Assigns and returns the enumerated objects after grouping the input parameters. Group; Delay

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 products by categoryid.

Note: from P in db. Products indicates that the product object is retrieved from the table. Group P by P. categoryid into G indicates that P is classified by the categoryid field. The result is named G. Once it is renamed again, the scope of P ends. Therefore, only select g can be selected. Of course, you do not need to rename it. You can write it like this:

 
VaR q = from P in db. Products Group P by P. categoryid;

We use the following representation:

If you want to traverse all records in a category, the following code is displayed:

 
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 };

Note: In this LINQ statement, there are two properties: categoryid and G. The essence of this anonymous class is to repackage the returned result set. Encapsulate g property into a complete group. As shown in:

To traverse all records in an anonymous class, do the following:

 
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 maximum unit price of each categoryid.

Note: first, sort by categoryid to determine the products with the largest unit price in each product category. Take out 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 for each categoryid.

Note: first, sort by categoryid to determine the minimum unit price of products in each product category. Take out the categoryid value and assign the unitprice value to minprice.

5. Average Value
 
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 obtain the average unit price of each categoryid.

Note: category by categoryid is used to retrieve the value of categoryid and the average unit price of each category product.

6. Sum
 
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 total unit price of each categoryid.

Note: category by categoryid is used to retrieve the value of categoryid and the total unit price of each product category.

7. Count
 
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 obtain the number of products in each categoryid.

Note: category by categoryid is used to retrieve the categoryid value and the quantity of products under each category.

8. 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 obtain the number of products that are out of stock in each categoryid.

Note: first, sort by categoryid to get the categoryid value and the number of out-of-stock items of each category. In the count function, lambda expressions are used. P in lambda expressions represents an element or object in the group, that is, a product.

9. Where restrictions
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: queries IDs and product quantities with the product quantity greater than 10 based on the product ID group. In this example, after the group by clause, use the WHERE clause to find all categories of at least 10 products.

Note: when translated into SQL statements, the where condition is nested in the outermost layer.

10. 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: Group products by categoryid and supplierid.

Note: products and suppliers are classified. After by, an anonymous class is created. Here, the key is actually a class object. The key contains two properties: categoryid and supplierid. You can use g. Key. categoryid to traverse the value of categoryid.

11. 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 of less than or equal to 10.

Note: whether the unit price is more than 10 categories. The result is divided into two types: greater than one type, smaller than or equal to the other type.

Exists/In/any/all/contains operator

Applicable scenarios: Used to determine elements in a set and further narrow down the scope.

Any

Note: It is used to determine whether an element in a set meets a certain condition without delay. (If the condition is null, true is returned if the set is not null. Otherwise, false is returned ). There are two forms: simple form and conditional form.

1. Simple Form:

Only customers without orders are returned:

 
VaR q = from C in db. MERs where! C. Orders. Any () Select C;

The 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]. [MERs] as [t0] Where not (exists (select null as [empty] from [DBO]. [orders] as [T1] Where [T1]. [customerid] = [t0]. [customerid])
2. Conditional form:

Only the following types of out-of-stock products are returned:

VaR q = from C in db. categories where c. Products. Any (P => P. discontinued) Select C;

The 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

Determines whether all elements in a set meet a certain condition without delay.

1. Conditional form
 
VaR q = from C in dB. Customers where c. Orders. All (O => O. shipcity = C. City) Select C;

Statement Description: In this example, all orders are sent to customers in the city where they are located or customers who have not placed orders.

Contains

Note: It is used to determine whether a collection contains a certain element without delay. It connects 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: searches for orders of the "arout", "bolid", and "fissa" customers. First, an array is defined and linq ins is used in LINQ to SQL. The array contains all the mermerids, that is, all the mermerids in the returned results are in this set. That is, in. You can also put the definition of an array in a LINQ to SQL statement. For example:

 
VaR q = (from o in dB. orders where (New String [] {"arout", "bolid", "fissa "}). contains (O. customerid) Select O ). tolist ();

Not contains:

 
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. MERs. 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 the customer who contains an order with orderid 10248.

2. contains multiple values:
String [] cities = new string [] {"Seattle", "London", "Vancouver", "Paris"}; var q = dB. MERs. where (P => cities. contains (P. city )). tolist ();

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

To sum up, we illustrate the following statements:

Group by/having
Group data; Delay

Any
Used to determine whether an element in a set meets a certain condition without delay.

All
Used to determine whether all elements in a set meet a certain condition without delay

Contains
Used to determine whether a collection contains a certain element without delay.

This series of links: navigation to the LINQ Series

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.