返回模型集合作为输出

时间:2012-08-23 08:14:58

标签: vb.net collections model

我只是想创建一个函数来返回一组用户。但是,为了能够稍后将项添加到我使用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

如何解决这些问题?

1 个答案:

答案 0 :(得分:1)

让你的方法返回ArrayList

Function getDoctorsList() As ArrayList()

Array创建ArrayList

Return userCollection.ToArray()

或最佳解决方案,让您的方法返回IEnumerable(Of User)

Function getDoctorsList() As IEnumerable(Of User)

您还应该使用List(of User)代替ArrayList,因为它是类型安全的(并且更加清晰),并且它还实现了IEnumerable(Of User)


修改

使用IEnumerable(of Users)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