首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何使用List(Of t)填充DataTable或将List(Of t)转换为DataTable?

要使用List(Of t)填充DataTable或将List(Of t)转换为DataTable,您可以按照以下步骤操作:

  1. 首先,确保您已经添加了对System.Data.DataSetExtensions.dll的引用。
  2. 然后,您可以使用以下代码将List(Of t)转换为DataTable:
代码语言:vb
复制
Imports System.Data
Imports System.Data.DataSetExtensions

Module Module1
    Sub Main()
        Dim list As List(Of Person) = New List(Of Person)
        list.Add(New Person With {.Name = "John", .Age = 30})
        list.Add(New Person With {.Name = "Jane", .Age = 25})

        Dim table As DataTable = ToDataTable(list)

        Console.WriteLine("Name\tAge")
        For Each row As DataRow In table.Rows
            Console.WriteLine("{0}\t{1}", row("Name"), row("Age"))
        Next
    End Sub

    Public Function ToDataTable(Of T)(ByVal list As List(Of T)) As DataTable
        Dim table As DataTable = New DataTable()
        Dim properties As PropertyInfo() = GetType(T).GetProperties()

        For Each propertyInfo As PropertyInfo In properties
            table.Columns.Add(propertyInfo.Name, propertyInfo.PropertyType)
        Next

        For Each item As T In list
            Dim row As DataRow = table.NewRow()
            For Each propertyInfo As PropertyInfo In properties
                row(propertyInfo.Name) = propertyInfo.GetValue(item)
            Next
            table.Rows.Add(row)
        Next

        Return table
    End Function
End Module

Public Class Person
    Public Property Name As String
    Public Property Age As Integer
End Class

这段代码首先定义了一个名为Person的类,并创建了一个List(Of Person)。然后,它使用ToDataTable函数将List(Of Person)转换为DataTable。最后,它遍历DataTable的每一行并将其输出到控制台。

在这个示例中,我们使用了System.Data.DataSetExtensions.dll中的扩展方法AsEnumerable()和CopyToDataTable()。这些方法可以让您轻松地将List(Of t)转换为DataTable。

需要注意的是,这个示例使用了Visual Basic语言编写,如果您使用的是C#,请根据语言特性进行相应的修改。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的沙龙

领券