Search code examples
c#linqdatatablelinq-group

DataTable group the result


I want to group in Datatable by Name, LastName and the rest should be in same row. Can someone help me with it?

My DataTable:

 Name   LastName    1    3    2
 kiki    ha         FF
 lola    mi             AA
 ka      xe                   UU
 kiki    ha                   SS

I want to have DataTable group by Name:

Name   LastName   1    3     2
kiki    ha        FF         SS 
lola    mi             AA 
ka      xe                   UU

My new code:

var result11 = from t1 in newtable.AsEnumerable()
               group t1 by new { Name = t1.Field<String>("Name"), LastName = t1.Field<String>("LastName") } into grp
               select new
               {
                   Name = grp.Key.Name,
                   LastName = grp.Key.LastName,

                   //Something must be there     
               };

Solution

  • Add these lines instead of the comment (//something must be there):

    C1 = String.Join(",", grp.Select(r=>r.Field<String>("1"))),
    C2 = String.Join(",", grp.Select(r=>r.Field<String>("2"))),
    C3 = String.Join(",", grp.Select(r=>r.Field<String>("3")))
    

    to get three new columns on the output that aggregate values from the columns 1, 3 and 2.

    If you have multiple values in one of the columns for a group, all the values will be shown and separated by comma (,).

    If you are sure that there's at most one value per column per group, then you can simply do:

    C1 = grp.Max(r => r.Field<String>("1")),
    C3 = grp.Max(r => r.Field<String>("3")),
    C2 = grp.Max(r => r.Field<String>("2"))