Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
665 views
in Technique[技术] by (71.8m points)

vb.net - convert datatable to class

I am trying to convert any datatable to existing class

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim x = dt_to_class_v1(Of class1)(dt_item)
    Dim y = dt_to_class_v2(Of class1)(dt_item)
End Sub

Dim stopwatch1 As New Stopwatch
Dim stopwatch2 As New Stopwatch

Function dt_to_class_v2(of t As New)(dt As DataTable) As List(Of t)
    stopwatch1.Start
    Dim oLists As New List(Of t)

    Dim col_count = oLists.GetType.GetProperties.Length -1
    For rows_count = 0 To dt.Rows.Count - 1
        Dim oST As New t
        For ix = 0 To col_count - 1
            Dim s_name = oST.GetType.GetProperties()(ix).Name
            Dim dt_svalue = dt(rows_count)(s_name)
            If IsDBNull(dt_svalue)
                dt_svalue = DBNull.Value
                oST.GetType.GetProperties()(ix).SetValue(oST, Nothing, Nothing)
            Else
                oST.GetType.GetProperties()(ix).SetValue(oST, dt_svalue, Nothing)
            End If
        Next ix
        oLists.Add(oST)
    Next rows_count
    stopwatch1.Stop
    MsgBox(stopwatch1.ElapsedMilliseconds)
    Return oLists
End Function

Function dt_to_class_v1(of T As New)(dt As DataTable) As List(Of T)
    stopwatch2.Start
    Dim items As IList(Of Class1) = dt_item.AsEnumerable().[Select](Function(row) New Class1 With {
    .id = row.Field(Of Integer)("id"),
    .name = row.Field(Of String)("name")}).ToList()
    stopwatch2.Stop
    MsgBox(stopwatch2.ElapsedMilliseconds)
    Return items
End Function

Class class1
    Property id     As Integer
    Property name   As String
End Class

dt_item is datatable with 9000 rows and 42 fields

dt_to_class_v2

  • is using reflection
  • no need to know what are the properties type or name
  • its slow. 4 seconds

dt_to_class_v1

  • its (querying itself as the poster said it do)
  • there is need to know the property type and name each time I pass datatable
  • its supper super super fast : 2 millisecond

Can I modify dt_to_class_v1 so I can send any datatable without I have to manually create property name and type ?

question from:https://stackoverflow.com/questions/65937888/convert-datatable-to-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...