VB.NET - 多维数组列表

5
我已经成功创建了一些一维数组列表,但我无法想出一个多维数组列表的方法。
这是我的目标:
我有一个包含5列的数据库(mdb),我希望每行都在一个数组列表中。
在PHP中,我通常会这样做: $array[$field1] = array($field2,$field3,$field4,$field5);
请问我该如何在vb.net中完成同样的操作,以便在需要检索特定行(row1)的项目时可以调用它?
对于单个维度,我可以执行以下操作,但我不知道如何将更多字段添加到单个数组行中:
    Dim tmpArrayX As New ArrayList
    tmpArrayX.Add(field(0))
    tmpArrayX.Add(field(1))
    etc...
2个回答

18
如果你想使用 ArrayList,只需将其项包含其他 ArrayList

或者你可以使用普通数组:

Dim multiArray(2, 2) As String
multiArray(0, 0) = "item1InRow1"
multiArray(0, 1) = "item2InRow1"
multiArray(1, 0) = "item1InRow2"
multiArray(1, 1) = "item2InRow2"

虽然我个人更喜欢使用List

Dim multiList As New List(Of List(Of String))
multiList.Add(New List(Of String))
multiList.Add(New List(Of String))

multiList(0).Add("item1InRow1")
multiList(0).Add("item2InRow1")
multiList(1).Add("item1InRow2")
multiList(1).Add("item2InRow2")

编辑:如何查找行:

Dim listIWant As List(Of String) = Nothing
For Each l As List(Of String) In multiList
    If l.Contains("item1InRow2") Then
        listIWant = l
        Exit For
    End If
Next

2
这样做是可以的,但是如何搜索一个项目并返回索引呢?比如我这样做: multiList(0).Add("item1InRow1") multiList(0).Add("item2InRow1") multiList(1).Add("item1InRow2") multiList(1).Add("item2InRow2")如何搜索"item1InRow2"并返回索引# "1",以便我可以查询数组中的其他列? - Joe
1
@Joe:可以通过循环来实现,我已经在我的答案中添加了一个简单的示例。可能还有一些不错的Linq方法,但我还没有太多使用过。 - Hans Olsson
1
一个(2,3)的列表怎么样?我无法实现它!你能给个例子吗?谢谢。 - Behzad
1
@Behzad: 只需要在其他两个行下面添加另一行,如 'multiList(0).Add("item3InRow1")'。不确定我是否理解您的问题,如果您创建一个新问题描述您的确切问题可能会更好(您始终可以链接到此问题以显示上下文)。 - Hans Olsson
2
@Behzad:是的,但有一定限制。如果您要存储数百万个项目,阅读此问题可能会很有用:https://dev59.com/cWsz5IYBdhLWcg3weHgA - Hans Olsson
显示剩余3条评论

4

这样可以在运行时添加行...已经测试过,它是有效的!

Dim multiList As New List(Of List(Of String))
Dim ListRow As Integer = 0

For each record in some_source 
  dim Country as string = record.country 'from some source 
  dim Date as Date = record.Date 'from some source 
  dim Venue as string = record.Venue 'from some source 
  dim Attendance as string = record.Attendance 'from some source 

  multiList.Add(New List(Of String))
  multiList(ListRow).Add(Country)
  multiList(ListRow).Add(Date)
  multiList(ListRow).Add(Venue)
  multiList(ListRow).Add(Rating)
  multiList(ListRow).Add(Attendance)
  ListRow = ListRow + 1
next

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接