8

我已经阅读了很多关于这个主题的帖子;其中还有最近的.NET - 将通用集合转换为数据表。不幸的是,一切都无济于事。

我有一个通用的结构集合:

Private Structure MyStruct
Dim sState as String
Dim lValue as Long
Dim iLayer as Integer
End Structure

Dim LOStates As New List(Of MyStruct)

我需要用这个结构列表填充 DataTable,但不知道如何去做。我在 Visual Studio 2008 中使用 vb.net。

任何见解将不胜感激

4

3 回答 3

19

您链接的代码假定成员被声明为属性。你没有声明属性。你可以让它与反射一起工作:

Imports System.Reflection
...

      Public Shared Function ConvertToDataTable(Of T)(ByVal list As IList(Of T)) As DataTable
        Dim table As New DataTable()
        Dim fields() As FieldInfo = GetType(T).GetFields()
        For Each field As FieldInfo In fields
          table.Columns.Add(field.Name, field.FieldType)
        Next
        For Each item As T In list
          Dim row As DataRow = table.NewRow()
          For Each field As FieldInfo In fields
            row(field.Name) = field.GetValue(item)
          Next
          table.Rows.Add(row)
        Next
        Return table
      End Function
于 2009-11-27T00:52:06.240 回答
7

我有与@SamSelikoff 相同的问题,移至 GetProperties:

Public Shared Function ConvertToDataTable(Of t)(
                                                  ByVal list As IList(Of t)
                                               ) As DataTable
    Dim table As New DataTable()
    If Not list.Any Then
        'don't know schema ....
        Return table
    End If
    Dim fields() = list.First.GetType.GetProperties
    For Each field In fields
        table.Columns.Add(field.Name, field.PropertyType)
    Next
    For Each item In list
        Dim row As DataRow = table.NewRow()
        For Each field In fields
            dim p = item.GetType.GetProperty(field.Name)
            row(field.Name) = p.GetValue(item, Nothing)
        Next
        table.Rows.Add(row)
    Next
    Return table
End Function
于 2014-07-14T15:15:55.970 回答
0

如果有人正在处理可空类型,请遵循 @Hans Passant 函数:

For Each field As FieldInfo In fields
' Extra check for nullable
If field.FieldType.AssemblyQualifiedName.Contains("System.Nullable") Then
    ' Insert proper type
    If field.FieldType.AssemblyQualifiedName.Contains("System.DateTime") Then
       table.Columns.Add(field.Name, Type.GetType("System.DateTime"))
    End If
Else
    table.Columns.Add(field.Name, field.FieldType)
End If
Next

价值观:

For Each item As T In list
Dim row As DataRow = table.NewRow()
For Each field As FieldInfo In fields
    ' Check if value is null
    If field.GetValue(item) is nothing Then
        Continue For
    End If
    row(field.Name) = field.GetValue(item)
Next
table.Rows.Add(row)
Next
于 2020-10-02T09:04:13.307 回答