如何使用List(Of t)或将List(Of t)转换为DataTable来填充DataTable? [英] How to fill a DataTable with a List(Of t) or convert a List(Of t) to a DataTable?
问题描述
我有一个通用的结构集合:
私有结构MyStruct
Dim sState as String
Dim lValue as Long
Dim iLayer as Integer
结束结构
Dim LOStates As New List (Of MyStruct)
我需要用这个结构列表填充一个DataTable,但不知道如何去做这个我在Visual Studio 2008中使用vb.net。
任何见解将不胜感激
您链接的代码假定成员被声明为属性。您没有声明属性。您可以使用Reflection进行工作:
导入System.Reflection
...
公共共享函数ConvertToDataTable(Of T)(ByVal list As IList(Of T))As DataTable
Dim table As New DataTable()
Dim fields()As FieldInfo = GetType(T).GetFields( )
对于每个字段作为FieldInfo在字段
table.Columns.Add(field.Name,field.FieldType)
下一个
对于每个项目作为T在列表
Dim row As DataRow = table.NewRow()
对于每个字段As FieldInfo在字段
row(field.Name)= field.GetValue(item)
下一个
table.Rows 。添加(行)
下一个
返回表
结束函数
I have read many posts on this topic; among them and most recently .NET - Convert Generic Collection to Data Table. Unfortunately, all to no avail.
I have a generic collection of structures :
Private Structure MyStruct
Dim sState as String
Dim lValue as Long
Dim iLayer as Integer
End Structure
Dim LOStates As New List(Of MyStruct)
I need to fill a DataTable with this list of structures but have no idea how to go about doing this. I am using vb.net in Visual Studio 2008.
Any insights will be greatly appreciated
The code you linked assumes the members are declared as properties. You didn't declare properties. You can make it work with Reflection:
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
这篇关于如何使用List(Of t)或将List(Of t)转换为DataTable来填充DataTable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!