Tuesday, April 12, 2016

Apply LINQ Grouping and Sum aggregate to a Datatable Object (C#)

Here's the C# version of this post. Apply LINQ Grouping and Sum aggregate to a Datatable Object (VB.NET)
Code:
 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
DataTable dt = new DataTable("tblEntTable");
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("amount", typeof(decimal));
dt.Rows.Add(new object[] {
    "1",
    100.51
});
dt.Rows.Add(new object[] {
    "1",
    200.52
});
dt.Rows.Add(new object[] {
    "2",
    500.24
});
dt.Rows.Add(new object[] {
    "2",
    400.31
});
dt.Rows.Add(new object[] {
    "3",
    600.88
});
dt.Rows.Add(new object[] {
    "3",
    700.11
});
 
var results = (from orders in dt.AsEnumerable()
            group orders by orders.Field<string>("ID") into g
            select new{
                ID = g.Key,
                Amount = g.Sum(r => r.Field<decimal>("amount"))
            }).OrderBy(tkey => tkey.ID).ToList();
 
dgvSum.DataSource = results;

Output:

0 comments:

Post a Comment