0

Is there a way to write a Linq statement to find duplication in Column B, and only find it when Column A has duplicated values then add the value of Column B to the Column where the duplication is found. Any help is appreciated thanks.

RecordID CartID Quantity ProductID 1 11 3 3 2 12 5 6 3 11 6 3 

Delete record 3 and add 6 to the Quantity of RecordID 1 so that it becomes:

RecordID CartID Quantity ProductID 1 11 9 3 2 12 5 6 
1
  • 1
    "add the value of Column B to the Column where the duplication is found" What does that mean? Commented Jun 20, 2011 at 16:15

1 Answer 1

6
 var records = (from i in list group i by i.CartID into g select new Item() { RecordID = g.Min(o => o.RecordID), CartID = g.Key, Quantity = g.Sum(o => o.Quantity), ProductID = g.Min(o => o.ProductID) }).ToList(); 

This sums all the quantity of items with the same CartId creating only the min occurent RecordId and ProductId as you asked. Selecting the min ProductId is something I needed to do to make the query work.

That is why I think you miss some grouping on ProductId...

You did not ask for this, but I think this is what you want (because it makes common sense to not group apples and pears together). (It gives the same result on the sample data provided but for different ProductsIds it will have different results.

 var records = (from i in list group i by new { cartID = i.CartID, prodID = i.ProductID } into g select new Item() { RecordID = g.Min(o => o.RecordID), CartID = g.Key.cartID, Quantity = g.Sum(o => o.Quantity), ProductID = g.Key.prodID }).ToList(); 

This groups by CartID and ProductId. Multi-field grouping in Linq is achieved with anonymous types.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for using .GroupBy, and also for noting that what the author probably wants is to group by CartId + ProductId.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.