Question

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     
               };
Était-ce utile?

La 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"))

Autres conseils

If you want a DataTable as result, this gives your desired result:

var lastNameGroups = from row in table1.AsEnumerable()
                     group row by new {
                        Name= row.Field<String>("Name"), 
                        LastName = row.Field<String>("LastName")
                     } into LastNameGroups
                     select LastNameGroups;

var table2 = table1.Clone();
foreach (var lng in lastNameGroups)
{
    var row = table2.Rows.Add();
    row.SetField("Name", lng.Key.Name);
    row.SetField("LastName", lng.Key.LastName);
    var ones = lng.Where(r => !string.IsNullOrEmpty(r.Field<String>("1")));
    if(ones.Any())
        row.SetField("1", ones.First().Field<String>("1"));
    var twos = lng.Where(r => !string.IsNullOrEmpty(r.Field<String>("2")));
    if (twos.Any())
        row.SetField("2", twos.First().Field<String>("2"));
    var threes = lng.Where(r => !string.IsNullOrEmpty(r.Field<String>("3")));
    if (threes.Any())
        row.SetField("3", threes.First().Field<String>("3"));
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top