vb.net 多维列表 - vb

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21578974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 16:40:38  来源:igfitidea点击:

multi dimensional list - vb

vb.netlist

提问by user1562652

I have a problem that can't solve...

我有一个无法解决的问题...

I have the set of data, which i want to add in two dimensional list (in Visual Basic)

我有一组数据,我想将其添加到二维列表中(在 Visual Basic 中)

the result of sql query is:

sql查询的结果是:

ID   value1 value2
0001  a      10
0001  b      10
0002  a      30
0002  b      20
0002  c      15
0003  a       5

....

....

so, i want add all elements into two dimensional list:

所以,我想将所有元素添加到二维列表中:

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

and I need a vb code that will add elemenets with different ID's to different lists of one two dimensional list

我需要一个 vb 代码,它将具有不同 ID 的元素添加到一个二维列表的不同列表中

thank you :)

谢谢你 :)

result must be:

结果必须是:

in first list elements 1 and 2
in the second list elements 3,4,5
in the third list the last element

回答by Tim Schmelter

You should use a DataTableinstead, then you just have to use a DataAdapterto fill it and Linq-To-DataSetto get your ID-Groups and List(Of DataTable):

您应该使用 aDataTable代替,然后您只需要使用 aDataAdapter来填充它并Linq-To-DataSet获取您的 ID-Groups 和List(Of DataTable)

Dim table = New DataTable()
Using con = New SqlClient.SqlConnection("Connection-String")
    Using da = New SqlDataAdapter("SQL-Query", con)
        da.Fill(table)
    End Using
End Using

Dim idGroups = From row In table
               Let id = row.Field(Of String)("ID")
               Group row By id Into Group
Dim idTables As List(Of DataTable) = idGroups.
    Select(Function(x) x.Group.CopyToDataTable()).
    ToList()

Since you are using .NET 2 LINQ is not an option. Here is an approach using a Dictionaryinstead of a Listwhere the key is the ID and the value is the DataTable:

由于您使用的是 .NET 2 LINQ 不是一个选项。这是一种使用 aDictionary而不是 a的方法,List其中键是 ID,值是DataTable

Dim idTables As New Dictionary(Of String, DataTable)
For Each row As DataRow In table.Rows
    Dim id As String = DirectCast(row("ID"), String)
    Dim dt As DataTable = Nothing
    If Not idTables.TryGetValue(id, dt) Then
        dt = table.Clone() ' empty table with same schema '
        idTables.Add(id, dt)
    End If
    dt.ImportRow(row)
Next

This does not require the resultset to be ordered by the ID.

这不需要按 ID 对结果集进行排序。