user1590636
user1590636

Reputation: 1194

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?

Upvotes: 2

Views: 1995

Answers (2)

fcuesta
fcuesta

Reputation: 4520

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);
    }

Upvotes: 2

alc
alc

Reputation: 1557

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.

Upvotes: 1

Related Questions