【问题标题】:Compare two lists 2D and determine differences VB.NET比较两个二维列表并确定差异 VB.NET
【发布时间】:2012-05-02 17:37:29
【问题描述】:

我声明我的二维列表:

Dim _invoiceitems As New List(Of List(Of String))
Dim _dbitems As New List(Of List(Of String))

每个列表都是这样填充的:

要填写的示例代码:

_invoiceitems.Add(New List(Of String))
_invoiceitems(0).Add("Code #")
_invoiceitems(0).Add("Quantity")

好吧,现在我需要一个名为 (_changesitems) 的第三个列表,请注意这个结果的不同之处: 如果找到,则为数量减法的结果(dbitems - invoiceitems)。

我怎样才能得到这个结果?

【问题讨论】:

  • 为什么不使用字典而不是二维列表?
  • 原谅我的无知,但是您可以根据我的例子举一些例子吗?
  • @JohnNuñez:字典是键值对的集合。我相信 volody 建议使用IDictionary(Of String, IList(Of String))。这将允许您通过使用“invoiceitem”作为键来查找您的“dbitems”集合,而不必通过无意义的整数(例如 _invoiceItems("invoice1").Add("Quantity") 与 _invoiceItems(0).Add("Quantity"))索引到您的 2D 列表集合。 LINQ 可用于获取识别差异的排除集。

标签: vb.net arrays visual-studio


【解决方案1】:

以下代码将生成您正在寻找的结果:

Private Function getChangesItems(ByVal invoiceItems As Dictionary(Of String, Integer), ByVal dbItems As Dictionary(Of String, Integer)) As Dictionary(Of String, Integer)
    Dim changesItems As Dictionary(Of String, Integer) = New Dictionary(Of String, Integer)()
    Dim allCodes As List(Of String) = New List(Of String)()
    allCodes.AddRange(invoiceItems.Keys)
    allCodes.AddRange(dbItems.Keys)
    For Each code As String In allCodes
        If Not changesItems.ContainsKey(code) Then
            Dim dbQuantity As Integer = 0
            Dim invoiceQuantity As Integer = 0
            If dbItems.ContainsKey(code) Then
                dbQuantity = dbItems(code)
            End If
            If invoiceItems.ContainsKey(code) Then
                invoiceQuantity = invoiceItems(code)
            End If
            Dim changeQuantity As Integer = dbQuantity - invoiceQuantity
            If changeQuantity <> 0 Then
                changesItems.Add(code, changeQuantity)
            End If
        End If
    Next
    Return changesItems
End Function

我使用字典而不是其他人推荐的列表。只要您的数据只包含一个代码和一个值,字典就更合适了。如果您有更多列,我建议创建一个包含每列属性的类,然后制作该类类型的列表,而不是简单的二维字符串列表。这样做会更安全且更易于阅读。

【讨论】:

  • 其实我已经无法用语言来形容他们的帮助了,你的算法在项目中非常有用,由衷感谢+UP
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-26
  • 1970-01-01
  • 1970-01-01
  • 2013-04-25
  • 1970-01-01
  • 2018-01-12
  • 2019-05-15
相关资源
最近更新 更多