Home > DeveloperSection > Forums > Getting count of all repeated rows in a datatable in C#
Andrew Watson
Andrew Watson

Total Post:39

Points:273
Posted on    January-19-2015 10:30 PM

 ASP.Net C# 
Ratings:


 1 Reply(s)
 547  View(s)
Rate this:

I am filling a dataset by running a stored procedure, and i am filling a datatable from the dataset.

DataSet RawDataSet = DataAccessHelper.RunProcedure("storedprocedureName");

//this will just return the dataset by running the procedure

DataTable RankTable = RawDataSet.Tables[0];

The Datatable has the below values:

Kamlakar   Login   6/24/2014

Kamlakar Login   6/25/2014

Vinu Game    6/26/2014

Vinu    Login   6/27/2014

Dilip   Login   6/28/2014

Dilip   Game    6/29/2014

Vinu     Login   6/30/2014

Vinu     Login   7/1/2014

Dilip    Game    7/2/2014

Kamlakar    Login   7/3/2014

Kamlakar    Login   7/4/2014

Kamlakar     Game    7/5/2014

I want to parse this dataTable and get how many times everyone has done an action, i.e how many times each row is repeated:

Kamlakar    Login  3

Vinu    Game   2

Vinu    Login  4

Kamlakar    Login  1

Kamlakar    Game   2

I am new to C#. This can be done using count(*) in SQL but I need to do this using C#. Please let me know if there are any ways to achieve this.

I have searched SO but all posts are related to removing the duplicates/finding the duplicates, which does not solve my purpose.



jayprakash sharma
jayprakash sharma

Total Post:117

Points:821
Posted on    January-19-2015 11:47 PM

You can achieve that using LINQ like:

var query = RankTable.AsEnumerable()

                    .GroupBy(r => new { Name = r.Field<string>("Name"), Action = r.Field<string>("Action") })

                    .Select(grp => new

                    {

                        Name = grp.Key.Name,

                        Action = grp.Key.Action,

                        Count = grp.Count()

                    });

Here Name is assumed to be the column name for first column, and Action is assumed to be name of second column which has values like login, game etc.

For output use:

foreach (var item in query)

{

    Console.WriteLine("Name: {0}, Action: {1}, Count: {2}",item.Name, item.Action,item.Count);

}

 


Don't want to miss updates? Please click the below button!

Follow MindStick