我试图创建一个函数,基本上返回具有以下结构的数组:(String, String, Integer)
起初,我使用SortedList(Of String, SortedList(Of String,Integer)),但这似乎是一个巨大的浪费,因为我不需要数组的数据。现在我在想一个矩形数组或一个数据表,但我不知道如何定义矩形数组使用多种类型,我不知道数据表运行时将有多快。
该函数将作为类函数被频繁使用,所以越快越好。下面是手头的代码片段:
Public Function GetDirectoryUsagePktTool(ByVal EIAFilePath As String, Optional ByVal PocketCount As Integer = 120) As SortedList(Of String, SortedList(Of String, Integer))
'Tracks the usage of all tools currently loaded in the machine against all tools in a specified directory
' ordered from least used to most used.
If Not IO.File.Exists(EIAFilePath) Then
'Handle invalid filepath
Throw New ApplicationException("{ToolStatus}GetDirectoryUsagePktTool: EIAFilePath doesn't exist")
End If
Dim EIADirectory As String = EIAFilePath.Remove(EIAFilePath.LastIndexOf(""))
'Get all Tool ID's with all of their FilePaths and Usage Counts per File
Dim dtl As SortedList(Of String, SortedList(Of String, Integer)) = GetDirectoryToolList(EIADirectory, EIAFilePath.Remove(0, EIAFilePath.LastIndexOf("") + 1))
'Get all Tool ID's currently loaded in each (associated with) Pocket ID
Dim pl As SortedList(Of String, String) = GetPocketList(PocketCount)
'Return object
Dim dupl As New SortedList(Of String, SortedList(Of String, Integer))
'Counter for Total Usage count
Dim cntr As Integer
'Enumerate through each Pocket ID
For Each Pocket As String In pl.Keys
'Reset Total Usage count
cntr = 0
'Verify existence of Tool ID in directory search
If Not IsNothing(dtl(Pocket)) Then
'Enumerate through File Paths using Pocket's Tool ID
For Each FilePath As String In dtl(pl(Pocket)).Keys
'Count Tool ID Usage
cntr += dtl(pl(Pocket))(FilePath)
Next
'Return object's Tool ID and Usage values
Dim tu As New SortedList(Of String, Integer)
'Probably not necessary, but ensure no overwriting or appended usage to Return Object
If IsNothing(dupl(Pocket)) Then
'Add reference of Pocket No. to Tool Group No and Total Count
' (Pocket ID, (Tool ID, Usage))
tu.Add(pl(Pocket), cntr)
dupl.Add(Pocket, tu)
End If
End If
Next
Return dupl
End Function
EDIT:忘记提到由于操作系统的限制,代码必须与。net 2.0及更早版本兼容。
解决方案:正如建议的那样,我创建了一个新的结构,并将其作为一个数组返回,因为我需要将Pocket ID的所有引用都引用到它的后续工具ID和用法。新的结构如下:
Structure PocketTools
Public PocketID As String
Public ToolGroupID As String
Public UsageCount As Integer
End Structure
返回对象声明:
'Return object
'Dim dupl As New SortedList(Of String, SortedList(Of String, Integer))
Dim dupl() As PocketTools
添加到返回对象
'Add reference of Pocket No. to Tool Group No and Total Count
' (Pocket ID, (Tool ID, Usage))
If IsNothing(dupl) Then
ReDim dupl(0)
Else
ReDim Preserve dupl(dupl.Length)
End If
dupl(dupl.Length - 1).PocketID = Pocket
dupl(dupl.Length - 1).ToolGroupID = pl(Pocket)
dupl(dupl.Length - 1).UsageCount = cntr
'tu.Add(pl(Pocket), cntr)
'dupl.Add(Pocket, tu)
我建议创建一个结构体或类来处理函数的返回类型。例如:
Structure MyStruct
Public Value1 As String
Public Value2 As String
Public Value3 As Integer
End Structure
听起来好像你根本不需要数组,如果它总是两个字符串和一个int。
不能对不同的数据类型使用多维数组,但可以使用Tuple
的数组(或列表)。
在我看来,在这种情况下,三个参数元组的数组似乎是一个显而易见的选择。