反射小应用之DataTable和List<T>互操作

 在程序中,往往会遇到一些小情况,就是数据库取出来的时候为了方便直接将数据通过存储在DataSet或DataTable中,这样做的一个后果是在日后的的对数据进行”细“操作时,就发现它可能没有List那么方便,而另外一些时候(比如使用SqlBulkCopy的时候)使用DataTable会比较方便。于是我...


code.google.com/p/yuhaibin/
code.google.com/p/zimijie2014/
code.google.com/p/ccaimi6820/
code.google.com/p/aieo02014/
code.google.com/p/lanxianzi2014/
code.google.com/p/mvj82910/
code.google.com/p/kalas92030/
code.google.com/p/caka93011/
code.google.com/p/kiucv28011/
code.google.com/p/ak89ack333/
code.google.com/p/ksakdi3/
code.google.com/p/oiwu29011/
code.google.com/p/mengqinghui2014/
code.google.com/p/cima9399/
code.google.com/p/laoic82888/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以回答你的问题。利用反射可以实现 DataTableList<T> 之间的转换。 首先,我们需要定义一个通用的方法,该方法可以将 List<T> 转换为 DataTable,也可以将 DataTable 转换为 List<T>。该方法的实现需要借助反射机制。 下面是将 List<T> 转换为 DataTable 的代码: ```csharp public static DataTable ConvertToDataTable<T>(List<T> list) { DataTable table = new DataTable(); PropertyInfo[] properties = typeof(T).GetProperties(); foreach (PropertyInfo property in properties) { table.Columns.Add(property.Name, property.PropertyType); } foreach (T item in list) { DataRow row = table.NewRow(); foreach (PropertyInfo property in properties) { row[property.Name] = property.GetValue(item, null); } table.Rows.Add(row); } return table; } ``` 上面的代码中,我们首先使用反射机制获取类型 T 的所有属性信息,然后使用这些属性信息创建 DataTable 的列。接着,我们遍历 List<T> 中的每个元素,使用反射获取元素的属性值,并将这些属性值添加到 DataRow 中,最后将 DataRow 添加到 DataTable 中。 下面是将 DataTable 转换为 List<T> 的代码: ```csharp public static List<T> ConvertToList<T>(DataTable table) where T : new() { List<T> list = new List<T>(); PropertyInfo[] properties = typeof(T).GetProperties(); foreach (DataRow row in table.Rows) { T item = new T(); foreach (PropertyInfo property in properties) { if (table.Columns.Contains(property.Name)) { property.SetValue(item, row[property.Name], null); } } list.Add(item); } return list; } ``` 上面的代码中,我们同样使用反射机制获取类型 T 的所有属性信息,然后遍历 DataTable 中的每个 DataRow,使用反射设置每个 DataRow 中对应的属性值,并将 T 对象添加到 List<T> 中。 希望这些代码可以帮助你解决问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值