介绍:List/IEnumerable转换到DataTable/DataView,以及DataTable转换到List

正文:

一、List<T>/IEnumerable转换到DataTable/DataView

方法一:

 /// <summary>
/// Convert a List{T} to a DataTable.
/// </summary>
private DataTable ToDataTable<T>(List<T> items)
{
var tb = new DataTable(typeof (T).Name); PropertyInfo[] props = typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in props)
{
Type t = GetCoreType(prop.PropertyType);
tb.Columns.Add(prop.Name, t);
} foreach (T item in items)
{
var values = new object[props.Length]; for (int i = ; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
} tb.Rows.Add(values);
} return tb;
} /// <summary>
/// Determine of specified type is nullable
/// </summary>
public static bool IsNullable(Type t)
{
return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
} /// <summary>
/// Return underlying type if type is Nullable otherwise return the type
/// </summary>
public static Type GetCoreType(Type t)
{
if (t != null && IsNullable(t))
{
if (!t.IsValueType)
{
return t;
}
else
{
return Nullable.GetUnderlyingType(t);
}
}
else
{
return t;
}
}

方法二:

 public static DataTable ToDataTable<T>(IEnumerable<T> collection)
{
var props = typeof(T).GetProperties();
var dt = new DataTable();
dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
if (collection.Count() > )
{
for (int i = ; i < collection.Count(); i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in props)
{
object obj = pi.GetValue(collection.ElementAt(i), null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
dt.LoadDataRow(array, true);
}
}
return dt;
}

二、DataTable转换到List

方法一:

 public static IList<T> ConvertTo<T>(DataTable table)
{
if (table == null)
{
return null;
} List<DataRow> rows = new List<DataRow>(); foreach (DataRow row in table.Rows)
{
rows.Add(row);
} return ConvertTo<T>(rows);
} public static IList<T> ConvertTo<T>(IList<DataRow> rows)
{
IList<T> list = null; if (rows != null)
{
list = new List<T>(); foreach (DataRow row in rows)
{
T item = CreateItem<T>(row);
list.Add(item);
}
} return list;
} public static T CreateItem<T>(DataRow row)
{
T obj = default(T);
if (row != null)
{
obj = Activator.CreateInstance<T>(); foreach (DataColumn column in row.Table.Columns)
{
PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);
try
{
object value = row[column.ColumnName];
prop.SetValue(obj, value, null);
}
catch
{ //You can log something here
//throw;
}
}
} return obj;
}

方法二:

把查询结果以DataTable返回很方便,但是在检索数据时又很麻烦,没有模型类型检索方便。

所以很多人都是按照以下方式做的:

1
2
3
4
// 获得查询结果 
DataTable dt = DbHelper.ExecuteDataTable(...); 
// 把DataTable转换为IList<UserInfo> 
IList<UserInfo> users = ConvertToUserInfo(dt);

问题:如果此系统有几十上百个模型,那不是每个模型中都要写个把DataTable转换为此模型的方法吗?

解决:能不能写个通用类,可以把DataTable转换为任何模型,呵呵,这就需要利用反射和泛型了

 using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Reflection;
namespace NCL.Data
{
/// <summary>
/// 实体转换辅助类
/// </summary>
public class ModelConvertHelper<T> where T : new()
{
public static IList<T> ConvertToModel(DataTable dt)
{
// 定义集合
IList<T> ts = new List<T>(); // 获得此模型的类型
Type type = typeof(T);
string tempName = ""; foreach (DataRow dr in dt.Rows)
{
T t = new T();
// 获得此模型的公共属性
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name; // 检查DataTable是否包含此列 if (dt.Columns.Contains(tempName))
{
// 判断此属性是否有Setter
if (!pi.CanWrite) continue; object value = dr[tempName];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
ts.Add(t);
}
return ts;
}
}
}

使用方式:

 // 获得查询结果
DataTable dt = DbHelper.ExecuteDataTable(...);
// 把DataTable转换为IList<UserInfo>
IList<UserInfo> users = ModelConvertHelper<UserInfo>.ConvertToModel(dt);

C# DataTable 和List之间相互转换的方法的更多相关文章

  1. 转 C# DataTable 和List之间相互转换的方法

    一.List/IEnumerable转换到DataTable/DataView 方法一: /// <summary> /// Convert a List{T} to a DataTabl ...

  2. C# DataTable 和List之间相互转换的方法(转载)

    来源:https://www.cnblogs.com/shiyh/p/7478241.html 一.List<T>/IEnumerable转换到DataTable/DataView 方法一 ...

  3. win32内核程序中进程的pid,handle,eprocess之间相互转换的方法

    很有用,收下以后方便查询. 原贴地址:http://bbs.pediy.com/showthread.php?t=119193 在win32内核程序开发中,我们常常需要取得某进程的pid或句柄,或者需 ...

  4. 关于数组和List之间相互转换的方法

    1.List转换成为数组:返回数组的运行时类型.如果列表能放入指定的数组.否则,将根据指定数组.如果指定的数组的元素比列表的多),那么会将存储列表元素的数组. 返回:包含列表元素的list.add(& ...

  5. DOS和UNIX文本文件之间相互转换的方法

    在Unix/Linux下可以使用file命令查看文件类型,如下: file dosfile.txt 使用dos2unix 一般Linux发行版中都带有这个小工具,只能把DOS转换为UNIX文件,命令如 ...

  6. json对象与javaBean,String字符创之间相互转换的方法

    原创:转载请注明出处 package com.allcam.system.utils; import com.fasterxml.jackson.databind.ObjectMapper; publ ...

  7. protobuf与json相互转换的方法

    google的protobuf对象转json,不能直接使用FastJson之类的工具进行转换,原因是protobuf生成对象的get方法,返回的类型有byte[],而只有String类型可以作为jso ...

  8. 路由其实也可以很简单-------Asp.net WebAPI学习笔记(一) ASP.NET WebApi技术从入门到实战演练 C#面向服务WebService从入门到精通 DataTable与List<T>相互转换

    路由其实也可以很简单-------Asp.net WebAPI学习笔记(一)   MVC也好,WebAPI也好,据我所知,有部分人是因为复杂的路由,而不想去学的.曾经见过一位程序猿,在他MVC程序中, ...

  9. python datetime和unix时间戳之间相互转换

                                python datetime和unix时间戳之间相互转换 1.代码:    import time    import datetime # ...

随机推荐

  1. (转载)FT232RL通信中断问题解决办法总结

    原文地址:http://cuiweidabing.blog.163.com/blog/static/66631928201101514021658/ FT232RL是FTDI(www.ftdichip ...

  2. 导入 RecyclerView 控件 的过程(Android 6.0)

    由于本人不熟悉Android Studio和java的思维方式,开发android studio的同事告诉我不太推荐使用ListView 而google 建议使用RecycleView ,经过了一顿查 ...

  3. mvc通过controller创建交互接口

    public JsonResult Home(string userName, string password, string type) { List<person> list = ne ...

  4. SSH in Python

    需要安装paramiko,paramiko需要PyCrypto , PyCrypto 需要GCC编译. 安装PyCrypto: 安装Mingw32,确认环境变量. 下载并编译PyCrypto - se ...

  5. DOM杂记

    INPUT 监听输入框值的变化:"input"

  6. 【原创】loadrunner12.53 录制脚本时 打不开网页或者打开网页慢?

          问题描述: 之前刚装12.5版本时候,用 WebTours测试过,应用程序选择自己本地IE浏览器.exe程序,输入url地址就可以成功录制了 . 但是由于公司网络配置环境改变了(猜测),现 ...

  7. 你还记得windows workflow foundation吗

    很多年前,windows workflow foundation还叫WWF,而直译过来的名称让很多人以为它就是用来开发工作流或者干脆就是审批流的. 博主当年还是个懵懂的少年,却也知道微软不会大力推一个 ...

  8. Effective objective-c 2.0阅读笔记

    这本书非常的好,看完后,感触挺深,总结纪录一下,针对ios开发的备忘: 注:分类和原著有些不同,自己总结学习用的,仅供参考.   系统篇: 了解oc起源:继承c,由Smalltalk演化而来.动态语言 ...

  9. Python应用科学计算和图表绘制

    今天更新了两个python模块,一个是用于科学计算的numpy模块,另一个是用于绘图的matplotlib模块 python安装模块还是很方便的,安装了pip之后直接使用"pip insta ...

  10. 【Python】Celery异步处理

    参考:http://www.cnblogs.com/znicy/p/5626040.html 参考:http://www.weiguda.com/blog/73/ 参考:http://blog.csd ...