Search code examples
c#datatable

Merge duplicate row in one with other column in c#


I have a DataTable that contain duplicate row with difference value in one column. like this:

enter image description here

So, I want merge duplicate PersonId in one row where PersonId and OrginalDate and ConvertedDate is same. like this:

enter image description here

It is possible that one person has even more records in one date

Update:

Note: I don't want delete duplicate records. If you pay close attention to the photos, I want to merge duplicate records into another table with more columns


Solution

  • I found my answer

    var groups = dataTable.AsEnumerable().GroupBy(row => new
     {
       PersonId = row.Field<double>("PersonId"),
       OrginalDate = row.Field<double>("OrginalDate")
     });
    
    var maxItems = groups.Max(x => x.Count()) / 2;
    DataTable pivot= new DataTable();
    pivot.Columns.Add("PersonId", typeof(int));
    pivot.Columns.Add("OrginalDate", typeof(int));
    pivot.Columns.Add("GregorianConvertedDate", typeof(DateTime));
    pivot.Columns.Add("PersianConvertedDate", typeof(string));
    
    for (int i = 1; i <= maxItems; i++)
    {
      pivot.Columns.Add("EnterTime" + i, typeof(TimeSpan));
      pivot.Columns.Add("ExitTime" + i, typeof(TimeSpan));
    }
    
    foreach (var group in groups)
    {
      DataRow newRow = tempDataTable.Rows.Add();
      newRow["PersonId"] = group.First()["PersonId"];
      newRow["OrginalDate"] = group.First()["OrginalDate"];
      newRow["GregorianConvertedDate"] = group.First()["GregorianConvertedDate"];
      newRow["PersianConvertedDate"] = group.First()["PersianConvertedDate"];
    
      for (int i = 0; i < group.Count() / 2; i++)
      {
        newRow["EnterTime" + (i + 1)] = group.Skip(2 * i).First().Field<string>("ConvertedTime");
        newRow["ExitTime" + (i + 1)] = group.Skip((2 * i) + 1).First().Field<string>("ConvertedTime");
       }
    }
    

    Many thanks to @jdweng