如何使用List(Of t)或将List(Of t)转换为DataTable来填充DataTable?

编程入门 行业动态 更新时间:2024-10-28 18:22:25
本文介绍了如何使用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。

任何见解将不胜感激

解决方案

您链接的代码假定成员被声明为属性。您没有声明属性。您可以使用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 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?

本文发布于:2023-11-08 16:36:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569902.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   如何使用   或将   DataTable   List

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!