/// <summary>
/// List转换为DataTable对象
/// </summary>
public class ListTranTableModel
{
/// <summary>
/// 新增的列名称
/// </summary>
public string addColumName { get; set; }
/// <summary>
/// 新增列的默认信息
/// </summary>
public TableCloumDInfo tableCloumDInfo { get; set; }
}

  /// <summary>
/// 列的默认信息
/// </summary>
public class TableCloumDInfo
{
//列的数据类型
public Type dataType { get; set; }
//列的默认值
public object defaultValue { get; set; }
}
  /// <summary>
/// 批量导入信息基类
/// </summary>
public class DatableBulk_ImportBase
{
/// <summary>
/// 重命名的列集合
/// </summary>
public Dictionary<string, string> PropertyRenameDic { get; set; }
/// <summary>
/// 要指定输出的列名称
/// </summary>
public string[] PropertyName { get; set; }
/// <summary>
/// 数据类型
/// </summary>
public string Category { get; set; }
/// <summary>
/// 批量导入信息时的说明信息
/// </summary>
public string ErrorInfo { get; set; }
}
    /// <summary>
/// 批量导入信息数据Table属性操作对象
/// </summary>
public class DatableProperty : DatableBulk_ImportBase
{
}
public static class ListTranDataTableHelper
{
/// <summary>
/// 将集合类转换成DataTable
/// </summary>
/// <param name="list">集合</param>
/// <returns></returns>
private static DataTable ToDataTableTow(IList list)
{
DataTable result = new DataTable();
if (list.Count > )
{
PropertyInfo[] propertys = list[].GetType().GetProperties(); foreach (PropertyInfo pi in propertys)
{
result.Columns.Add(pi.Name, pi.PropertyType);
}
foreach (object t in list)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
object obj = pi.GetValue(t, null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
} /// <summary>
/// DataTable 转换为List 集合
/// </summary>
/// <typeparam name="TResult">类型</typeparam>
/// <param name="dt">DataTable</param>
/// <returns></returns>
public static List<T> ToList<T>(this DataTable dt) where T : class, new()
{
//创建一个属性的列表
List<PropertyInfo> prlist = new List<PropertyInfo>();
//获取TResult的类型实例 反射的入口
Type t = typeof(T); //获得TResult 的所有的Public 属性 并找出TResult属性和DataTable的列名称相同的属性(PropertyInfo) 并加入到属性列表
Array.ForEach<PropertyInfo>(t.GetProperties(), p => { if (dt.Columns.IndexOf(p.Name) != -) prlist.Add(p); }); //创建返回的集合
List<T> oblist = new List<T>(); foreach (DataRow row in dt.Rows)
{
//创建TResult的实例
T ob = new T();
//找到对应的数据 并赋值
prlist.ForEach(p => { if (row[p.Name] != DBNull.Value) p.SetValue(ob, row[p.Name], null); });
//放入到返回的集合中.
oblist.Add(ob);
}
return oblist;
} /// <summary>
/// 转化一个DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static DataTable ToDataTable<T>(this IEnumerable<T> list)
{
//创建属性的集合
List<PropertyInfo> pList = new List<PropertyInfo>();
//获得反射的入口
Type type = typeof(T);
DataTable dt = new DataTable();
//把所有的public属性加入到集合 并添加DataTable的列
Array.ForEach<PropertyInfo>(type.GetProperties(), p => { pList.Add(p); dt.Columns.Add(p.Name, p.PropertyType); });
foreach (var item in list)
{
//创建一个DataRow实例
DataRow row = dt.NewRow();
//给row 赋值
pList.ForEach(p => row[p.Name] = p.GetValue(item, null));
//加入到DataTable
dt.Rows.Add(row);
}
return dt;
} /// <summary>
/// 将泛型集合类转换成DataTable /// </summary>
/// <typeparam name="T">集合项类型</typeparam> /// <param name="list">集合</param>
/// <returns>数据集(表)</returns>
public static DataTable ToDataTable<T>(IList<T> list)
{
return ToDataTable<T>(list,new Dictionary<string, string>(), null); } /**/ /// <summary>
/// 将泛型集合类转换成DataTable
/// </summary>
/// <typeparam name="T">集合项类型</typeparam>
/// <param name="list">集合</param>
/// <param name="="propertyRenameDic">需要指定重命名的列集合</param>
/// <param name="propertyName">需要返回的列的列名</param>
/// <returns>数据集(表)</returns>
public static DataTable ToDataTable<T>(IList<T> list, Dictionary<string, string> propertyRenameDic, params string[] propertyName)
{
List<string> propertyNameList = new List<string>();
if (propertyName != null)
{
propertyNameList.AddRange(propertyName);
if (propertyRenameDic.Count>)
{
foreach (var item in propertyRenameDic)
{
propertyNameList.Remove(item.Key);
propertyNameList.Add(item.Value);
}
}
}
DataTable result = new DataTable();
if (list.Count > )
{
PropertyInfo[] propertys = list[].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
if (propertyNameList.Count == )
{
result.Columns.Add(pi.Name, pi.PropertyType);
}
else
{
if (propertyNameList.Contains(pi.Name))
result.Columns.Add(pi.Name, pi.PropertyType);
if (propertyRenameDic.Keys.Contains(pi.Name))
{
if (propertyNameList.Contains(propertyRenameDic[pi.Name]))
result.Columns.Add(propertyRenameDic[pi.Name], pi.PropertyType);
} }
} for (int i = ; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
if (propertyNameList.Count == )
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
else
{
if (propertyRenameDic.Keys.Contains(pi.Name))
{
if (propertyNameList.Contains(pi.Name) || propertyNameList.Contains(propertyRenameDic[pi.Name]))
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
}
else
{
if (propertyNameList.Contains(pi.Name))
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
} }
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
} /// <summary>
/// 将DataTable新增几列并指定默认值
/// </summary>
/// <param name="vTable">源表</param>
/// <param name="list">增加的列集合</param>
/// <returns></returns>
public static DataTable AddColums(DataTable vTable, List<ListTranTableModel> list)
{
foreach (var item in list)
{
//添加一新列,其值为默认值
DataColumn dc = new DataColumn(item.addColumName, item.tableCloumDInfo.dataType);
dc.DefaultValue = item.tableCloumDInfo.defaultValue;
dc.AllowDBNull = false;//这在创建表的时候,起作用,在为已有表新增列的时候,不起作用
vTable.Columns.Add(dc);
}
return vTable;
}
}

调用举例

 DataTable dt = ListTranDataTableHelper.ToDataTable(listv, DatableProperty.PropertyRenameDic);

封装一个List集合和datatable相互转换的工具类(可对指定列进行重命名并且指定输出列)的更多相关文章

  1. List集合和JSON互转工具类

    public class JsonListUtil { /** * List<T> 转 json 保存到数据库 */ public static <T> String list ...

  2. 浅析Android Camera开发中的三个尺寸和三种变形 (贡献一个自适配Picturesize和Previewsize的工具类)

    转至 (http://blog.csdn.net/yanzi1225627/article/details/17652643) 经常听人问Camera开发中,各种变形问题,今天有空就在此梳理总结下. ...

  3. DataSet转换为泛型集合和DataRow 转成 模型类

    public static class TransformToList { /// <summary> /// DataSet转换为泛型集合 /// </summary> // ...

  4. 一个具有缓存数据功能的HttpWebRequest工具类

    背景:一个公共站点中的数据,供其它子站点共享,为了提高性能,简单实现了Http 1.1的缓存功能 特点:可以缓存Html数据到内存中;缓存具有过期时间;缓存过期后,通过再确认的方式来决定是否更新缓存; ...

  5. 方法:一个简单的读取配置文件.properties的工具类 JAVA

    import java.util.ResourceBundle; public class ConfigHelper { private static ConfigHelper instance; p ...

  6. 一个很好的通用 excel 导出工具类

    此类用主要 jxl +注解+流 实现扩展性很强,jxl性能会比poi好一点,值得我们学习. package oa.common.utils; import java.io.OutputStream; ...

  7. [Unity]C#中 将XML和实体类之间进行相互转换的工具类

    using System; using System.Xml; using System.Xml.Serialization; using System.IO; namespace LOTool { ...

  8. Android 开发 记录一个DP、PX、SP转换工具类

    public class UnitConversionUtil { /** * 根据手机分辨率从DP转成PX * @param context * @param dpValue * @return * ...

  9. spring 中 PO与DTO相互转换的工具类

    public class BeanMapper { /** * 持有Dozer单例, 避免重复创建DozerMapper消耗资源. */ private static DozerBeanMapper ...

随机推荐

  1. Uva 10294 Polya

    #include <bits/stdc++.h> using namespace std; typedef long long LL; int gcd(int a,int b) { ? a ...

  2. MariaDB修改端口号

    修改端口号 打开my.ini文件

  3. js函数在frame中的相互的调用

    框架编程概述一个HTML页面可以有一个或多个子框架,这些子框架以<iframe>来标记,用来显示一个独立的HTML页面.这里所讲的框架编程包括框架的自我控制以及框架之间的互相访问,例如从一 ...

  4. 【题解】UVA756 Biorhythms (中国剩余定理)

    UVA756:https://www.luogu.org/problemnew/show/UVA756 思路 几乎是裸的中国剩余定理模板题 但是需要注意的是此题并不是求最小正整数解 而是求大于d的解 ...

  5. 自己做的HTML

    <html> <body background="http://img1.imgtn.bdimg.com/it/u=821335874,2927998559&fm= ...

  6. 关于Echarts的原生js获取DOM元素与动态加载DOM元素的冲突问题

    1.前言: 最近在做的看板项目,因为需要循环加载后台数据,并且用Echarts做数据呈现,所以jQuery和angular等库统统靠边站,Echarts用的是原生js获取DOM元素,至于诸多不兼容等深 ...

  7. Jedis连接redis客户端

    1 单点的redis利用jedis客户端连接 如何连接 //1 利用jedis连接对象操作redis @Test public void test01(){ //构造一个具有连接信息的jedis对象 ...

  8. 删除Navicat在注册表信息

    @echo offecho 正在删除navicat注册表REG DELETE HKEY_CURRENT_USER\Software\PremiumSoft\Data /fREG DELETE HKEY ...

  9. [USACO5.2]蜗牛的旅行Snail Trails(有条件的dfs)

    题目描述 萨丽·斯内尔(Sally Snail,蜗牛)喜欢在N x N 的棋盘上闲逛(1 < n <= 120). 她总是从棋盘的左上角出发.棋盘上有空的格子(用“.”来表示)和B 个路障 ...

  10. PG进程结构和内存结构

    ​ 本文主要介绍PostgreSQL数据库(后文简称PG)进程结构和内存结构,物理结构将在后续继续整理分享. ​ 上图描述了PG进程结构.内存结构和部分物理结构的内容.图中的内容包含了两个部分: PG ...