0

我只是想创建一个函数来返回一组用户。但是,为了以后能够将项目添加到集合中,我使用了arrayList,但最后我得到了一个错误 Type ArrayList cannot be converted to 1-Dimensional array of Users

这是我的代码:

Function getDoctorsList() As Users()
    Dim userCollection As New ArrayList
    Dim sql = "SELECT * FROM '" + _tblName + "' WHERE usertype = 'doctor'"
    Dim dr As SqlDataReader = dbHelper.ExecuteAndGetReader(sql)
    While dr.Read
        Dim user As New Users
        user.Id = IIf(IsDBNull(dr("id")), 0, dr("id"))
        user.UserName = IIf(IsDBNull(dr("username")), "", dr("username"))
        user.UserNin = IIf(IsDBNull(dr("user_nin")), 0, dr("user_nin"))
        user.UserType = IIf(IsDBNull(dr("usertype")), "", dr("usertype"))
        user.Password = IIf(IsDBNull(dr("password")), "", dr("password"))
        userCollection.Add(user)
    End While
    Return userCollection
End Function

如何解决此类问题?

4

1 回答 1

1

要么让你的方法返回一个ArrayList

Function getDoctorsList() As ArrayList()

创建一个Array你的ArrayList

Return userCollection.ToArray()

或者,最好的解决方案是让您的方法返回一个IEnumerable(Of User)

Function getDoctorsList() As IEnumerable(Of User)

您还应该使用 aList(of User)而不是 a ArrayList,因为它是类型安全的(并且更清晰)并且它还实现了IEnumerable(Of User).


编辑

IEnumerable(of Users)使用and 的示例DataRowExtensions

Function GetDoctorsList() As IEnumerable(of Users)
    Dim sql = "SELECT * FROM '" + _tblName + "' WHERE usertype = 'doctor'"
    Dim table = new DataTable()
    table.Load(dbHelper.ExecuteAndGetReader(sql))
    Return (from row in table.AsEnumerable()
            select new User() With
            {
               .Id = row.FieldOf(Of Integer)("id"),
               .UserName = row.Field(Of String)("username"),
               .UserNin = row.Field(Of Integer)("user_nin"),
               .UserType = row.Field(Of String)("usertype"),
               .Password = row.Field(Of String)("password")
            }).ToList()
End Function
于 2012-08-23T08:16:16.393 回答