如何使用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?

查看:161
本文介绍了如何使用List(Of t)或将List(Of t)转换为DataTable来填充DataTable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了很多关于这个话题的帖子其中包括最近的 .NET - 将通用集合转换为数据表。不幸的是,这一切都无济于事。



我有一个通用的结构集合:

 私有结构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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆