Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

consolidate a certain field value from duplicate item in a list

Posted on 2013-06-27
8
Medium Priority
?
364 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
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 2000 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

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…

721 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