Use Group by 1

Source: Internet
Author: User

1. Simple Form:

 
 
  1. var q =
  2. from p in db.Products
  3. group p by p.CategoryID into g
  4. select g;

Statement Description: LINQ uses group by to classify 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.

2. Maximum Value

 
 
  1. var q =
  2. from p in db.Products
  3. group p by p.CategoryID into g
  4. select new {
  5. g.Key,
  6. MaxPrice = g.Max(p => p.UnitPrice)
  7. };

Statement Description: uses 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.

3. Minimum value

 
 
  1. var q =
  2. from p in db.Products
  3. group p by p.CategoryID into g
  4. select new {
  5. g.Key,
  6. MinPrice = g.Min(p => p.UnitPrice)
  7. };

Statement Description: uses group by and min to find the lowest unit price of 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.

4. Average Value

 
 
  1. var q =
  2. from p in db.Products
  3. group p by p.CategoryID into g
  4. select new {
  5. g.Key,
  6. AveragePrice = g.Average(p => p.UnitPrice)
  7. };

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.

5. Sum

 
 
  1. var q =
  2. from p in db.Products
  3. group p by p.CategoryID into g
  4. select new {
  5. g.Key,
  6. TotalPrice = g.Sum(p => p.UnitPrice)
  7. };

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.