vb.net - 如何用List(Of t)填充DataTable或将List(Of t)转换为DataTable?

标签 vb.net datatable structure generic-list

我已经阅读了很多有关该主题的文章;其中最近一次是.NET - Convert Generic Collection to Data Table。不幸的是,一切都无济于事。

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

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。

任何见解将不胜感激

最佳答案

您链接的代码假定成员被声明为属性。您没有声明属性。您可以使其与反射一起使用:

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

关于vb.net - 如何用List(Of t)填充DataTable或将List(Of t)转换为DataTable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1805626/

相关文章:

c++ - 保证结构成员之间没有填充以将结构用作数组

php - 如何让 index.php 控制 PHP 中的任何内容

c# - 在 WinForms 选项卡控件中,我如何知道您正在从/向哪个选项卡移动?

vb.net - 使用 System.Net.Sockets SendFile 后检索数据

mysql - 有没有一个非常简单的MySQL表前端?

vb.net - 使用 NAudio 流式传输非 PCM 原始音频

mysql - 错误消息 "ORA-02270: no matching unique or primary key for this column-list"

c# - foreach row in datatable 为每一列添加一个asptablerow和asptablecell

c - 指针/结构

sql - 将 c# DataTable 作为参数传递给 MS SQL Server 2008 中的存储过程