vb.net 如何用 List(Of t) 填充 DataTable 或将 List(Of t) 转换为 DataTable?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1805626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to fill a DataTable with a List(Of t) or convert a List(Of t) to a DataTable?
提问by 8thWonder
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.
我已经阅读了很多关于这个主题的帖子;其中包括最近的.NET - 将通用集合转换为数据表。可惜,一切都无济于事。
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.
我需要用这个结构列表填充数据表,但不知道如何去做。我在 Visual Studio 2008 中使用 vb.net。
Any insights will be greatly appreciated
任何见解将不胜感激
回答by Hans Passant
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
回答by dani herrera
I have same issue than @SamSelikoff, moved to GetProperties:
我有与@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