Solved

consolidate a certain field value from duplicate item in a list

Posted on 2013-06-27
8
321 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 74

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 74

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
 
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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 74

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 74

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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

757 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now