Donate

Apply LINQ Grouping And Sum Aggregate To A Datatable Object (C#)

Good day!


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:
Apply LINQ Grouping And Sum Aggregate To A Datatable Object (C#)

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.