用于排序和过滤的数据结构

Gre*_*edo 4 sorting collections excel vba arraylist

是否有任何数据结构可以通过有效的对象排序和过滤来访问?

对于排序,这System.Collections.ArrayList是完美的,因为我只是添加了大量的类 whichImplement IComparable.Sort(). 但是我找不到.Filter()方法,因为可能存在一些文章提示(第 9.3 节)。

是否有用于过滤和排序自定义对象的良好集合类型?最好是用预编译语言编写的东西。


一个简单的对象看起来像这样:

Implements IComparable                           'requires mscorlib.dll, allows sorting

Public itemIndex As Long                        'simplest, sorting by an integer value

Private Function IComparable_CompareTo(ByVal obj As Variant) As Long
    'for sorting, itemindex is based on current grid sorting mode
    If TypeOf obj Is clsGridItem Then
        Dim other As clsGridItem: Set other = obj
        Dim otherIndex As Long: otherIndex = other.itemIndex
        Dim thisIndex As Long: thisIndex = Me.itemIndex
        If thisIndex > otherIndex Then
            IComparable_CompareTo = 1
        ElseIf thisIndex < otherIndex Then
            IComparable_CompareTo = -1
        Else
            IComparable_CompareTo = 0
        End If
    Else
        Err.Raise 5                              'obj is wrong type
    End If

End Function
Run Code Online (Sandbox Code Playgroud)

我有一个用随机索引填充的数组列表。当然,任何东西都可以进入比较例程(我实际上Select Case用于不同的比较例程,基于类的不同属性)。一个简单的过滤器循环可以检查何时IComparable_CompareTo = 0

ash*_*awg 5

ArrayList 对象内置了排序功能,而过滤无非是“仅使用您需要的项目”。

例如,这会用随机数填充一个对象,然后过滤结果以仅显示那些可被 整除的结果42

Option Explicit

Sub testSort()

    Const filter = 42
    Dim arr As Object, x As Long, y As Long
    Set arr = CreateObject("System.Collections.ArrayList")

    ' populate array with 100 random numbers
    For x = 1 To 420
        arr.Add Int(Rnd() * 10000)
    Next

    ' "sort" array
    arr.Sort

    ' dump array to immediate window; "filter" to show only even numbers
    For x = 0 To arr.Count - 1
        If arr(x) / filter = arr(x) \ filter Then
            'item mnatches filter
            Debug.Print "arr(" & x & ") = " & arr(x)
            y = y + 1
        End If
    Next x

    Debug.Print "Returned " & y & " sorted results (Filter=" & filter & ")"
End Sub
Run Code Online (Sandbox Code Playgroud)

其他可能性

您还没有共享的细节是什么,你需要过滤器和如何,但我进一步思考它,你可能要检查这些了,看他们是否可以应用到你的任务:

  • @Greedo 似乎您想要的是从 VBA 代码传递委托/谓词的能力。那是做不到的。这个答案表明您需要自己进行循环。 (3认同)
  • 可爱的代码...... `arr(x) / filter = arr(x) \ filter` (2认同)