Solved

consolidate a certain field value from duplicate item in a list

Posted on 2013-06-27
8
336 Views
Last Modified: 2013-07-03
Hi EE,
    I come across a problem where i need to remove the duplicate code in a list, but sum up one of the field's value for that code.
I have a class:
Public Class Product
 pCode as string
 pQty as Integer
End Class

then I got a list of products:
Dim pList as new List (of Products)
pList.Add(New Products With {.pCode = "123", .pQty = 5}
pList.Add(New Products With {.pCode = "456", .pQty = 1}
pList.Add(New Products With {.pCode = "123", .pQty = 3}
pList.Add(New Products With {.pCode = "553", .pQty = 2}


I want my above list end up having 3 items
Code 123         456   553
Qty    8 (5+3)     1        2


is there a way to do this in LINQ? or any other  approaches are also fine.
0
Comment
Question by:miketonny
  • 4
  • 4
8 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39283239
Use a Group By query.

e.g.

Dim query = From entry In pList
            Group entry By entry.pCode Into Group
            Select New With {
                .Code = pCode,
                .Qty = Group.Sum(Function(item) item.pQty)
            }

For Each item In query
    Console.WriteLine("{0}: {1}", item.Code, item.Qty)
Next

Open in new window

0
 
LVL 2

Author Comment

by:miketonny
ID: 39283330
thx Kaufmed, this looks like the way to solve my issue.
however, when i try the above code with my product list, which the class has 10+ properties.
i got an error:
Name 'DocumentNumber' is either not declared or not in the current scope.      

   Dim query = From entry In psList _
            Group entry By entry._Code Into Group _
            Select New With {._Code = _Code, .pQty= Group.Sum(Function(item) item.pQty), _
                            .DocumentNumber = DocumentNumber}

Open in new window


select new with creates an anonymous type, what should i do to be able to use my existing type 'Product' ? because i have another 10 attributes for the product to remain the same.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39283392
You only demonstrated the need for two properties in the OP, and I got the impression that you needed an anonymous type based on your output example. You don't have to create an anonymous type; you can use your Product type. But I don't have a clear picture of how your desired output information relates to your Product type. Can you clarify?
0
The New “Normal” in Modern Enterprise Operations

DevOps for the modern enterprise offers many benefits — increased agility, productivity, and more, but digital transformation isn’t easy, especially if you’re not addressing the right issues. Register for the webinar to dive into the “new normal” for enterprise modern ops.

 
LVL 2

Author Comment

by:miketonny
ID: 39283408
Sorry abt that, is below a bit clearer?
I have a list of products may or maynot have duplicate codes,
I want to consolidate the duplicate codes in the list, adding _pQty for those duplicates and get a new list at the end.

Public Class Product
    Private _DocumentNumber As String
    Private _pQty As String
    Private _Description As String
    Private _Code As String
    Private _DocumentDate As String
    Private _CompanyPhone As String
    Private _ZEXTPARTNO As String
    Private _Weight As String
    Private _ZBIN2 As String
    Private _QtyOnHand As String
    Private _GroupNo As String
    Private _MyCompanyNo As String
    Private __LineNumber As Integer
    Private __UnitPriceExTax As String
End Class

Open in new window



I managed to do this in a for loop
    
  'All individual product lines are now added to list
  'Consolidate same product codes into the same line, sum up the qty
            Dim consolidatedList As New List(Of Product)
            For i As Integer = 0 To psList.Count - 1
                Dim currentPS As New Product
                currentPS = psList(i)
                Dim existCode As Boolean = consolidatedList.Any(Function(c) c._Code = currentPS._Code)
                If existCode = False Then
                    consolidatedList.Add(psList(i))
                Else
                    'Code already exists in consolidated list, sum up the quantity of the code
                    Dim indx As Integer
                    indx = consolidatedList.FindIndex(Function(f) f._Code = currentPS._Code)
                    consolidatedList(indx)._pQty= CDbl(consolidatedList(indx)._pQty) + CDbl(psList(i)._pQty)
                End If
            Next

Open in new window

0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39283422
What about the other properties (for Products with identical codes)? Will they be the same values across all instances of a Product, or can they differ? If they can differ, then a Group By may not work.
0
 
LVL 2

Author Comment

by:miketonny
ID: 39283469
they will be the same, only difference are the pQty.  that's why i wanted to merge them and sum up the pQty field.
0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 39284008
OK. Then a Group By should be fine. It should be along the lines of:

Dim query = From entry In pList
	    Group entry By
		entry.Code, entry.Description, entry.DocumentNumber, entry.DocumentDate, entry.CompanyPhone, entry.ZEXTPARTNO, entry.Weight, entry.ZBIN2, entry.QtyOnHand, entry.GroupNo, entry.MyCompanyNo, entry.LineNumber, entry.UnitPriceExTax Into Group
	    Select New Products With {
		.Description = Description,
		.DocumentNumber = DocumentNumber,
		.DocumentDate = DocumentDate,
		.CompanyPhone = CompanyPhone,
		.ZEXTPARTNO = ZEXTPARTNO,
		.Weight = Weight,
		.ZBIN2 = ZBIN2,
		.QtyOnHand = QtyOnHand,
		.GroupNo = GroupNo,
		.MyCompanyNo = MyCompanyNo,
		.LineNumber = LineNumber,
		.UnitPriceExTax = UnitPriceExTax,
		.Code = Code,
		.pQty = Group.Sum(Function(item) item.pQty)
	    }

Open in new window


If you also need to sum the QtyOnHand field, then you can remove it from the Group By clause, and then add another Group.Sum call that assigns to the QtyOnHand property in the Select, choosing item.QtyOnHand instead. That property will need to be numeric in type, of course. (Currently, it's a string.)
0
 
LVL 2

Author Closing Comment

by:miketonny
ID: 39298530
Awesome, thanks a bunch
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question