/// <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. Python变量和数据类型(入门2)

    转载请标明出处: http://www.cnblogs.com/why168888/p/6400809.html 本文出自:[Edwin博客园] Python变量和数据类型 一.整数 int = 20 ...

  2. iTunes备份路径,iTunes默认备份路径,iTunes修改备份路径

    1:当前iTunes版本: 2:帮助给出的答复: 3:修改的操作界面: 实际文件夹路径:

  3. Codeforces Round #333 (Div. 1)

    A. The Two Routes In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railw ...

  4. Spring Boot 配置文件详解:Properties和YAML

    一.配置文件的生效顺序,会对值进行覆盖: 1. @TestPropertySource 注解 2. 命令行参数 3. Java系统属性(System.getProperties()) 4. 操作系统环 ...

  5. Ubuntu14.04系统下无法连接Wi-Fi无线网以及安装BCM43142网卡驱动的解决方案

    1.问题描述 博主近日开始学习ROS,首先必装Linux操作系统,选择的是Ubuntu14.04,安装过程略过,直接讲问题.安装完系统之后发现一个重要问题,没法使用Wi-Fi,只能使用有线网络,而且网 ...

  6. Android学习笔记_5_文件操作

    1.Activity提供了openFileOutput()方法可以用于把数据输出到文件中,具体的实现过程与在J2SE环境中保存数据到文件中是一样的. package com.example.servi ...

  7. jdbc连接各种数据库字符串

    oracle driverClass:oracle.jdbc.driver.OracleDriver url:jdbc:oracle:thin:@127.0.0.1:1521:dbname mysql ...

  8. Javascript文件中的控制器I

    <!DOCTYPE html><html><head><meta http-equiv="Content-Type" content=&q ...

  9. 一个logstash引发的连环案,关于logstash提示:Reached open files limit: 4095, set by the 'max_open_files' option or default, files yet to open: 375248

    不多说,直接上问题.版本logstash-2.4.0,启动后提示错误: !!! Please upgrade your java version, the current version '1.7.0 ...

  10. SQL、T-SQL与PL-SQL的区别

    SQL.T-SQL与PL-SQL的区别 SQL是Structrued Query Language的缩写,即结构化查询语言.它是负责与ANSI(美国国家标准学会)维护的数据库交互的标准.作为关系数据库 ...