8th*_*der 6 vb.net datatable structure generic-list
我读了很多关于这个主题的帖子; 其中以及最近的.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)
Run Code Online (Sandbox Code Playgroud)
我需要用这个结构列表填充DataTable,但不知道如何去做.我在Visual Studio 2008中使用vb.net.
任何见解将不胜感激
Han*_*ant 17
您链接的代码假定成员被声明为属性.您没有声明属性.你可以使用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
Run Code Online (Sandbox Code Playgroud)
我有与@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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
62987 次 |
| 最近记录: |