views:

599

answers:

1

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 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.

+1  A: 

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()),
};
Bryan Watts
Very cool. Grouping was the key, plus I was trying to use Linq's aggregate method which apparently wasn't necessary. Thank ya sir!
Carter
Aggregate would work here, `String.Join` just happens to be a specific implementation we can leverage :-)
Bryan Watts
Yeah, that's what I gathered. Might try to aggregate it just to see if I can.
Carter