是否有任何数据结构可以通过有效的对象排序和过滤来访问?
对于排序,System.Collections.ArrayList
是完美的,因为我只是添加了 Implement IComparable
和 .Sort()
的类负载。但是我找不到 .Filter()
方法,因为可能存在一些 articles 提示(第 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
我有一个用随机索引填充的数组列表。当然,比较例程中可以包含任何内容(我实际上将
Select Case
用于不同的比较例程,基于类的不同属性)。一个简单的过滤器循环可以检查何时 IComparable_CompareTo = 0
最佳答案
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
其他可能性
您还没有分享关于您需要过滤的内容和方式的太多细节,但我正在进一步考虑,您可能想查看这些内容,看看它们是否可以应用于您的任务:
返回包含基于指定过滤条件的字符串数组子集的从零开始的数组
CreateObject("System.Collections.ArrayList")
(VB) 根据指定的类型
ArrayList
Class Constructors (VB)