在DataTable VB.Net 2005中选择不同的行和总和列

时间:2015-10-22 16:11:20

标签: vb.net visual-studio-2005

我有一个dataTable包含:

ID POCount POTotal
  A 1 10
  A 2 20
  B 4 10

我想得到一个新数据表的结果如下:
 ID POCount POTotal
  A 3 30
  B 4 10

如何使用数据表执行此操作? 我的项目是在VB.NET 2005中,我不能使用LINQ方法。 这样做的最佳方式是什么?

我找到了一个接近我想要的链接。但它只是跳过行而不是在id相似时对列进行求和。 http://www.dotnetfunda.com/forums/show/2603/how-to-remove-duplicate-records-from-a-datatable

1 个答案:

答案 0 :(得分:0)

LINQ可能更好 - 升级到后来的VS Express - 它是免费的!

这是一种使用类和Dictionery的方法

Public Class POSummary
    Public Property ID As String
    Public Property Count As Integer
    Public Property Total As Integer
    Sub New(POid As String, POcount As Integer, POtotal As Integer)
        ID = POid
        Count = POcount
        Total = POtotal
    End Sub
End Class
Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
    Dim pos As New List(Of POSummary)
    Dim po As New POSummary("A", 1, 10)
    pos.Add(po)
    po = New POSummary("A", 2, 20)
    pos.Add(po)
    po = New POSummary("B", 4, 10)
    pos.Add(po)

    Debug.Print("--data--")
    For Each p As POSummary In pos
        Debug.Print(p.ID & " " & p.Count & " " & p.Total)
    Next

    Dim pd As New Dictionary(Of String, POSummary)

    For Each p As POSummary In pos
        If Not pd.ContainsKey(p.ID) Then
            pd.Add(p.ID, p)
        Else
            pd(p.ID).Count += p.Count
            pd(p.ID).Total += p.Total
        End If
    Next
    Debug.Print("--totals--")
    For Each kvp As KeyValuePair(Of String, POSummary) In pd
        po = kvp.Value
        Debug.Print(po.ID & " " & po.Count & " " & po.Total)
    Next
    Stop
End Sub