数据表的列表(T)?

时间:2014-04-09 15:17:34

标签: .net vb.net

根据其他Stackoverflow的答案,我为测试编写了一个简单的列表和数据表转换,但是在调试中,数据集Visualizer并没有在数据表中显示任何内容。我错过了什么吗?这是代码:

    Public Class ObjectToTable
    Dim s As List(Of Events)
    Public Sub New(ByVal s As List(Of Events))
        Me.s = s
        s.Add(New Events("A"))
        s.Add(New Events("B"))
        s.Add(New Events("C"))
        s.Add(New Events("D"))
    End Sub
    Public Function GetTable() As DataTable
        Dim props As PropertyDescriptorCollection = TypeDescriptor.GetProperties(GetType(Events))
        For i As Integer = 0 To props.Count - 1
            Dim prop As PropertyDescriptor = props(i)
            myTable.Columns.Add(prop.Name, prop.PropertyType)
        Next
        Dim values As Object() = New Object(props.Count - 1) {}
        For Each Events As Events In s
            For i As Integer = 0 To values.Length - 1
                values(i) = props(i).GetValue(Events)
            Next
            myTable.Rows.Add(values)
        Next
        Return myTable
    End Function
End Class

...谢谢

1 个答案:

答案 0 :(得分:0)

如果您的问题是如何转换A list(of T) to a Datatable?,那么以下代码可能是更好的方法。

Imports System.Runtime.CompilerServices
Imports System.Reflection

<Extension()> _
Public Module Extensions

    <Extension()> _
    Public Function ToDataTable(Of T As Class)(data As List(Of T)) As DataTable
        Dim result As New DataTable()
        Dim type As Type = GetType(T)
        Dim list = (From p As PropertyInfo In type.GetProperties() Where (p.CanRead AndAlso (p.GetIndexParameters().Length = 0)) Select New With {.[Property] = p, .Column = New DataColumn(p.Name, p.PropertyType)})
        result.Columns.AddRange((From obj In list Select obj.Column).ToArray())
        If (Not data Is Nothing) Then
            result.BeginLoadData()
            Array.ForEach(Of T)(data.ToArray(), Function(item As T) result.Rows.Add((From obj In list Select obj.[Property].GetValue(item, Nothing)).ToArray()))
            result.EndLoadData()
        End If
        result.AcceptChanges()
        list = Nothing
        type = Nothing
        Return result
    End Function

End Module

<强>用法

Imports {YOUR.NAMESPACE}.Extensions

Dim list As New List(Of Events)({New Events("A"), New Events("B"), New Events("C"), New Events("D")})
Dim table As DataTable = list.ToDataTable()