'/*************************************************************** '类 名 称:ChangeToList '说 明:将DataTable转换成泛型集合 '命名空间:DAL '创建时间:2015年4月24日17:25:38 '作 者:郑浩 '小 组: '修改时间: '修 改 人: '版 本 号:V1.0 '****************************************************************/ Imports System.Reflection Imports System.Collections.Generic Public Class ChangeToList ''' <summary> ''' 将DataTable转换成泛型集合 ''' </summary> ''' <typeparam name="T">任意类型</typeparam> ''' <param name="dt">DataTable</param> ''' <param name="ts">集合</param> ''' <returns>集合</returns> ''' <remarks></remarks> Public Shared Function ConverToList(Of T As New)(dt As DataTable,ts As List(Of T)) '获得T的类型 Dim type As Type = GetType(T) '定义一个临时变量 Dim strTemp As String = String.Empty '遍历所有行数 For Each dr As DataRow In dt.Rows '定义类型变量act获取动态创建对象T的类型 Dim act As T = If((Nothing Is Nothing),Activator.CreateInstance(Of T),Nothing) '引用反射表示可获得对象的所有属性组成的集合 Dim propertys As PropertyInfo() = act.GetType.GetProperties() '定义array变量,接收propertys中含有的属性,并提供对属性propertys元数据访问 Dim array As PropertyInfo() = propertys Dim intCount As Integer = 0 '遍历所有对象属性 While intCount < array.Length 'length表示所有维数中元素的综合 'pr表示元素中含有的属性,并提供对数据访问 Dim pr As PropertyInfo = array(intCount) strTemp = pr.Name '列名=对象的属性名 If dt.Columns.Contains(strTemp) Then '判断此属性是否设置函数 If pr.CanWrite Then '该属性是否可写 Dim value As Object = dr(strTemp) '如果非空,则赋值给对象的属性 If value IsNot DBNull.Value Then '设置对象的属性值 pr.SetValue(act,value,Nothing) End If End If End If intCount += 1 Continue While End While '添加对象到泛型集合中 ts.Add(act) Next Return ts End Function End Class
''' <summary> ''' 查询卡表数据 ''' </summary> ''' <param name="enCard"></param> Public Function QueryData(ByVal enCard As cardEntity) As List(Of Entity.cardEntity) Implements ICardDAL.QueryData '实例化一个sqlHelper类 Dim helper As New sqlHelper '定义sql语句 Dim sql As String = "Select * from T_CardInfo" '定义DataTable Dim dt As New DataTable '定义泛型集合 Dim cardList As New List(Of Entity.cardEntity) dt = helper.ExeSelect(sql,CommandType.Text) '如果DataTable中行数大于0,说明有返回的数据,然后将DataTable转换成泛型集合 If dt.Rows.Count > 0 Then cardList = CType(ChangeToList.ConverToList(dt,cardList),Global.System.Collections.Generic.List(Of Global.Entity.cardEntity)) End If Return cardList End Function