1. Simple Form:
- var q =
- from p in db.Products
- group p by p.CategoryID into g
- 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
- 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: 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
- 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: 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
- 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.
5. 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)
- };