简体   繁体   中英

DataTable group by separated by comma

I have a datatable that looks like the following

cname  tname  text        allowgroupping
A      M      good        Yes
A      M      bad         Yes
A      M      ugly        Yes
B      N      sick        No
B      N      lovely      No
C      R      pathatic    Yes

I want to group the datatable by the first column cname so the result will look like

cname  tname      text                 allowgroupping
    A      M      good,bad,ugly        Yes
    B      N      sick,lovely          No
    C      R      pathatic             Yes

I have done it by looping each column and doing a lot of checks, but how can I do it using LINQ and save the result to a datatable?

The idea is to group the table per:

var groupedDB =
  from entry in dataTable
  group entry by entry.cName into entryGroup
  select new
  {
    cName = entryGroup.Key,
    tName = entryGroup.First().tName,
    text = String.Join(",", entryGroup.Select(_=>_.text)),
    allowGrouping = entryGroup.First().allowGrouping
  };

Of course, once you do that you'll see that you're making some bold assumptions about the tName and allowGrouping columns. Be sure that you mean to. If not, you should group by all three columns instead of just the cName .

You can do something like this:

    var query = from row in dataTable.AsEnumerable()
                group row by row["cname"] into g
                select new {    cname = g.Key,
                                tname = g.First()["tname"] ,
                                text = String.Join(", ", g.Select(r=>r["text"].ToString()).ToArray()),
                                allowgrouping = g.First()["allowgroupping"]
                };

    foreach (var row in query)
    {
        resultDataTable.Rows.Add(row.cname, row.tname, row.text, row.allowgrouping);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM