GROUP BY in datatable select using c#

2.4k Views Asked by At

I have a dataTable which has rows as shown in below image,enter image description here

I would like to write groupby statement with select on that datatable for getting output as below,

enter image description here

3

There are 3 best solutions below

3
On BEST ANSWER

Try this using LINQ in C#

var result = from tab in dt.AsEnumerable()
             group tab by tab["ApplicationNmae"]
                 into groupDt
                 select new
                 {
                     ApplicationNmae = groupDt.Key,
                     Sum = groupDt.Sum((r) => decimal.Parse(r["Count"].ToString()))
                 };

DataTable dt1 = new DataTable();
dt1 = dt.Clone();

foreach (var item in result)
{
    DataRow newRow = dt1.NewRow();
    newRow["ApplicationNmae"] = item.ApplicationNmae;
    newRow["Count"] = item.Sum;
    dt1.Rows.Add(newRow);
}

Grid.DataSource = dt1;

Ref: Group by in DataTable Column sum

0
On
select ApplicationName, count(*) from DataTableName
group by ApplicationName

where DataTableName should be replaced by the actual name of your table in the database, and ApplicationName should be replaced by the name of the column in that table that contains applicatin name

0
On

Simply this...

SELECT ApplicationName, COUNT(*) [Count]
FROM THETABLENAME
GROUP BY ApplicationName

or with ordering and filtering (where there is a duplication and order by the count)...

SELECT ApplicationName, COUNT(*) [Count]
FROM THETABLENAME
GROUP BY ApplicationName
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC