Linq to SQL: Combining objects through a summation of one field only
I have a set of objects that I'm returning via a Linq to SQL query. I'd like to modify the query so that I return a set of objects that are combined only when one of the fields match.
The relevant columns of my Products
DB table are CategoryID
and Quantity
. I'd like to combine the fields so that if the CategoryID
is identical, the Quantity
fields are summed up. However, I don't just want the sum - I need an object that has all the common fields (assume all other fields are identical for the query) so it ap开发者_如何学Gopears as only one object of type Product
.
Is this possible? (I'm using VB.net - but open to solutions that include database views, partial classes, etc)
It sounds like you want to Group on CategoryId and create a new Product based on aggregate data. E.g. (sorry if my VB is terrible):
From product In db.Products _
Group By CategoryID = product.CategoryID Into Group _
Select New Product With _
CategoryID = CategoryID, _
QuantityA = Group.Select(Function(p) p.QuantityA).Sum(), _
QuantityB = Group.Select(Function(p) p.QuantityB).Sum()
精彩评论