0

Please take a look at the code below:

Public Class PersonTest

    Public Function ListTest()
        Dim list As List(Of Person) = New List(Of Person)
        Dim p1 As Person = New Person(1, "Ian")
        Dim p2 As Person = New Person(2, "Steven")
        Dim p3 As Person = New Person(3, "Sharon")
        list.Add(p1)
        list.Add(p2)
        list.Add(p3)
        For Each p As Person In list
            MsgBox(p.IDNumber)
        Next

    End Function

End Class

Public Class Person
    Public IDNumber As Integer
    Public Name As String

    Public Sub New(ByVal id As Integer, ByVal name As String)
        IDNumber = id
        name = name
    End Sub

End Class

Public Class Form1

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim pt As PersonTest = New PersonTest
        pt.ListTest()
    End Sub
End Class

I expect the Message Box to print: 1,2,3 which it does. Can you confirm that List uses insertion order. I am planning to store the results of database queries in a list i.e:

SELECT * FROM Person ORDER BY ID

The SQL statement is ordered by ID. Can I assume that the List will also be ordered by ID?

The reason I ask is because the answerer to my question here: Data Access Layer returns DataTable, suggests using a List to return an object from a Data Access Layer.

4

3 回答 3

3

是的,列表将存储您输入的对象。见列表(T)。添加

将对象添加到 List(Of T) 的末尾。

于 2013-02-16T13:57:29.083 回答
2

您可以假设anIList将以这种方式行事,是的。除了枚举之外,它还提供索引,因此列表的类型需要保持不变以支持它。

但是,如果你想明确,你总是可以明确排序:

For Each p As Person In list.OrderBy(Function(pe) pe.IDNumber)
于 2013-02-16T13:58:25.030 回答
2

另一种选择是使用 a SortedList,它在内部根据指定的键和默认比较器维护其顺序(除非您提供自己的比较器)。

    Dim list As New SortedList(Of Integer, Person)

    Dim p1 As Person = New Person(1, "Ian")
    Dim p2 As Person = New Person(2, "Steven")
    Dim p3 As Person = New Person(3, "Sharon")
    list.Add(p3.IDNumber, p3)
    list.Add(p1.IDNumber, p1)
    list.Add(p2.IDNumber, p2)

    For Each p As Person In list.Values
        MsgBox(p.IDNumber)
    Next

我故意打乱了将项目添加到列表中的顺序。每当列表更改时,它都会运行排序算法以确保项目保持正确的顺序。根据您打算如何使用它,这可能会增加相当多的开销。

于 2013-02-16T15:45:52.817 回答