목록 (t)으로 데이터 가능을 채우거나 목록 (t)을 데이터 테이블로 변환하는 방법은 무엇입니까?
-
05-07-2019 - |
문제
이 주제에 대한 많은 게시물을 읽었습니다. 그들 중에서 가장 최근에 .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)
이 구조 목록으로 데이터 가능을 채워야하지만이 작업을 수행하는 방법을 전혀 모릅니다. 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
다른 팁
@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
제휴하지 않습니다 StackOverflow