【问题标题】:Find Common Values in several arrays, or lists VB.NET在几个数组或列表中查找公共值 VB.NET
【发布时间】:2011-12-23 16:20:18
【问题描述】:

Find common values in multiple arrays with PHP

几乎可以满足我的需要,但在 PHP 中,我需要 VB。

我的情况是我正在尝试创建一个基于多个库存位置的智能选股系统。

在开具发票时,我们会遍历已开具发票的商品并检查库存数据库中的可用库存。

如果发票上的所有项目都可以从库存位置 1 中挑选,那么所有项目都应该从库存位置 1 中挑选......等等。

如果除了一个或两个库存位置 1 中的所有大多数项目都可用,则从库存位置 1 中挑选所有库存,但应从可用库存最高的位置挑选的例外情况除外。

查找最高可用库存很简单,但我不知道如何分析多个位置的库存可用性并找到常见的库存位置。

我可以像这样创建一组数组

Item ID    |     Available Stock Locations
    1      |        2, 3, 5
    2      |        1, 2, 6
    3      |        2, 3, 4
    4      |        1, 2 ,3 

如何比较这些位置列表以发现 2 是所有四个位置的共同点?

其次,如果一件商品没有共同的库存位置,我将如何识别该商品以便我可以返回并找到它的最高可用库存水平?

【问题讨论】:

    标签: .net vb.net arrays


    【解决方案1】:

    就像在 PHP 中一样,您可以相交 数组来找到共同的值。感谢 LINQ,这在 VB 中相当容易:

    Dim array1 = {2, 3, 5}
    Dim array2 = {1, 2, 6}
    Dim array3 = {2, 3, 4}
    Dim array4 = {1, 2, 3}
    
    Dim commonItems = array1.Intersect(array2).Intersect(array3).Intersect(array4)
    

    commonItems 现在是一个 IEnumerable(Of Integer),包含所有常见的商店位置。

    【讨论】:

    • 注意:和我所有的 VB 代码示例一样,这个假设是 Option Explicit/Strict/Infer On
    • 看起来不错,但我遇到了错误,大概是因为我使用的是 .NET 2.0 框架? intersect is not a member of system.array
    • @JamieHartnoll Intersect 是一个 LINQ 扩展。您需要 .NET 3.5 或更高版本才能使用它。
    【解决方案2】:

    Linq 会更干净,但这种方法应该适用于 2.0...

    Dim arrX(2) As Integer
    arrX(0) = 0
    arrX(1) = 1
    arrX(2) = 2
    
    Dim arrY(2) As Integer
    arrY(0) = 0
    arrY(1) = 32
    arrY(2) = 2
    
    Dim arrZ(2) As Integer
    arrZ(0) = 10
    arrZ(1) = 2
    arrZ(2) = 22
    
    Dim arrCommon() As Integer
    
    For Each i As Integer In arrX
    
        For Each i2 As Integer In arrY
    
            If i = i2 Then
    
                For Each i3 As Integer In arrZ
    
                    If i2 = i3 Then
    
                        If arrCommon Is Nothing OrElse arrCommon.Length = 0 Then
    
                            ReDim arrCommon(0)
                            arrCommon(0) = i
    
                        Else
    
                            ReDim Preserve arrCommon(arrCommon.Length)
    
                            arrCommon(arrCommon.Length - 1) = i
    
                        End If
    
                    End If
    
                Next
    
            End If
    
        Next
    
    Next
    

    【讨论】:

    • 算法看起来不错,但为什么不使用List(Of Integer)?如果需要数组,您可以在完成后调用arrCommon = listCommon.ToArray() 创建一个。
    • 我也更喜欢通用列表,但决定只使用数组来实现这个例子,因为这就是问题中提到的。另外,我并不肯定泛型包含在 2.0 中。不过,您确实提出了一个有效的问题,因为使用 List(of Integer) 类型可以避免 ReDim 语句和 If Then 块之一。
    • 我想我现在被禁止在圣诞节之后使用电脑,但这看起来不错,除了一个缺陷,我似乎需要知道我有多少库存地点才能努力写作编码。我也在尝试使这个系统具有可扩展性,因此如果添加/删除位置,它需要灵活。
    猜你喜欢
    • 1970-01-01
    • 2015-12-15
    • 2011-07-15
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    • 2015-05-31
    • 2016-12-22
    • 1970-01-01
    相关资源
    最近更新 更多