Solved

consolidate a certain field value from duplicate item in a list

Posted on 2013-06-27
8
329 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
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
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

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
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.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

809 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