LINQ – Data source Group By Sum

 LINQ


            DataTable table = new DataTable();
            table.Columns.Add(“ID”, typeof(int));
            table.Columns.Add(“Percentage”, typeof(int));

            table.Rows.Add(1, 50);
            table.Rows.Add(1, 30);
            table.Rows.Add(2, 0);
            table.Rows.Add(2, 100);

            var result = (from p in table.AsEnumerable()
                          group p by p[“ID”] into r
                          select new
                          {
                              ID = r.Key,
                              Percentage = r.Sum((s) => decimal.Parse(s[“Percentage”].ToString()))
                          }).ToList();
_________________________________________________
INPUT :

ID | Percentage |
1       50
1       30
2         0
2       100

OUTPUT :

ID | Percentage |
1       80
2       100

Published by arjunpremier

Software Engineer, Blogger,

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Design a site like this with WordPress.com
Get started