Group and aggregate a list of objects
I have a list of data structured like this:
Field1 Field2 开发者_如何学编程Field3
1 1 "abc"
1 1 "def"
1 2 "123"
1 2 "456"
I want to be able to merge this data so I end up with a single record per Field1 & Field2 and with the Field3 data concatenated. So in the above case I would get:
Field1 Field2 Field3
1 1 "abcdef"
1 2 "123456"
I would like to use linq/query expressions for this.
var query =
from row in rows
group row by new { row.Field1, row.Field2 } into g
select new RowClass
{
Field1 = g.Key.Field1,
Field2 = g.Key.Field2,
Field3 = g.Aggregate(
new StringBuilder(),
(sb, grp_row) => sb.Append(grp_row.Field3))
.ToString()
}
精彩评论