-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
GroupBy-Sample-3.cs
52 lines (47 loc) · 1.83 KB
/
GroupBy-Sample-3.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System.Linq;
using System;
using System.Collections.Generic;
namespace Grouping
{
public class GroupBy3
{
//This sample uses group by to partition a list of products by category.
//Outputs to the console all products by category
public static void QuerySyntaxExample()
{
List<Product> products = Data.Products;
var orderGroups =
from p in products
group p by p.Category into g
select new { Category = g.Key, Products = g };
foreach (var i in orderGroups)
{
Console.WriteLine("-------------------");
Console.WriteLine($"Category={i.Category}:");
foreach (var p in i.Products)
{
var s = $"ProductID={p.ProductId}, Product Name={p.ProductName}, UnitPrice={p.UnitPrice}, UnitsInStock={p.UnitsInStock}";
Console.WriteLine(s);
}
}
}
//This sample uses group by to partition a list of products by category.
//Outputs to the console all products by category
public static void MethodSyntaxExample()
{
List<Product> products = Data.Products;
var orderGroups = products.GroupBy(p => p.Category,
(Key, g) => new { Category = Key, Products = g });
foreach (var i in orderGroups)
{
Console.WriteLine("-------------------");
Console.WriteLine($"Category={i.Category}:");
foreach (var p in i.Products)
{
var s = $"ProductID={p.ProductId}, Product Name={p.ProductName}, UnitPrice={p.UnitPrice}, UnitsInStock={p.UnitsInStock}";
Console.WriteLine(s);
}
}
}
}
}