开发者

How do I use Linq to group a DataTable by multiple rows/columns into a new datatable with duplicate rows concatenated?

God, Linq confuses me... I've found quite a few examples that do similar things to what I need, but I'm still getting all turned around. I have a table (we'll call it UngroupedTable) that looks 开发者_Python百科like this...

ID, Val1, Val2

0001, A, 1

0001, B, 2

0002, C, 3

0003, D, 4

0003, D, 5

I want to use Linq to build a table where essentially in GroupedTable the IDs would become unique and values for duplicated IDs get concatenated into their respective rows.

So, it'd look like this...

ID, Val1, Val2

0001, A B, 1 2

0002, C, 3

0003, D, 4 5

We'll call it GroupedTable.

What I've got certainly isn't close, but I'll post it anyway...

from row in passedInTable.AsEnumerable()
group row by new { ID = row.Field<string>("ID"), Val1 = row.Field<string>("Val1"), Val2 = row.Field<string>("Val2") } into groupedRow
select new
{
    ID = groupedRow.Key.ID,
    Val1 = groupedRow.Key.Val1,
    Val2 = groupedRow.Key.Val2
};

I think I could see how I could do what I need at this point with some for looping but I'm pretty sure it's do-able via Linq. Especially based on all the examples I see out there, using .sum() for number types.

Edit

I guess the ultimate question is, in that query up above, how do I aggregate the values for the val1 and val2 columns from within that select new block so it's selecting out the concatenated values.


You only need to group by the ID of the row. Then, concatenate all the values in each group:

from row in passedInTable.AsEnumerable()
group row by row.Field<string>("ID") into rowGroup
select new
{
    ID = rowGroup.Key,
    Val1 = String.Join(" ", rowGroup.Select(row => row.Field<string>("Val1")).ToArray()),
    Val2 = String.Join(" ", rowGroup.Select(row => row.Field<string>("Val2")).ToArray()),
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜