Home > database >  C# Datatable data to new datatable group by colum and count distinct
C# Datatable data to new datatable group by colum and count distinct

Time:08-29

I have a datatable like this:

idworker    idwork  idtask  task    tag
154         192     490     task 1  No
152         192     490     task 1  No
154         192     492     task 2  One
154         192     492     task 2  Two
154         192     492     task 2  Four
152         192     492     task 2  Three
152         192     492     task 2  Four
152         192     492     task 2  Five

and i need create a new datatable like this:

idwork  idtask  task    tag         count
192     490     task 1  No          2
192     492     task 2  One         1
192     492     task 2  Two         1
192     492     task 2  Three       1
192     492     task 2  Four        2
192     492     task 2  Five        1

Im a new programmer and i tried this solution: C# datatable Group by count and distinct but not works for me.

How i can get this?

Thanks!

CodePudding user response:

Hi I am assuming you want to group by idwork, idtask, task , tag these fields If so you can try this -

  DataTable result = new DataTable();
        result.Columns.Add("idwork", typeof(int));
        result.Columns.Add("idtask", typeof(int));
        result.Columns.Add("task", typeof(string));
        result.Columns.Add("tag", typeof(string));
        result.Columns.Add("count", typeof(int));
        result = dt.AsEnumerable()
                    .GroupBy(r => new { idwork = r["idwork"], idtask = r["idtask"], task = r["task"], tag = r["tag"] })
                    .Select(g =>
                    {
                        var row = result.NewRow();

                        row["idwork"] = g.Key.idwork;
                        row["idtask"] = g.Key.idtask;
                        row["task"] = g.Key.task;
                        row["tag"] = g.Key.tag;
                        row["count"] = g.Count();
                       

                        return row;

                    })
                    .CopyToDataTable();
  • Related