DataTableHelper
public class DataTableHelper
{
/// <summary>
/// 给DataTable增加一个自增列
/// 如果DataTable 存在 identityid 字段 则 直接返回DataTable 不做任何处理
/// </summary>
/// <param name="dt">DataTable</param>
/// <returns>返回Datatable 增加字段 identityid </returns>
public static DataTable AddIdentityColumn(DataTable dt)
{
if (!dt.Columns.Contains("identityid"))
{
dt.Columns.Add("identityid");
for (int i = 0; i < dt.Rows.Count; i++)
{
dt.Rows[i]["identityid"] = (i + 1).ToString();
}
}
return dt;
} /// <summary>
/// 检查DataTable 是否有数据行
/// </summary>
/// <param name="dt">DataTable</param>
/// <returns></returns>
public static bool IsHaveRows(DataTable dt)
{
if (dt != null && dt.Rows.Count > 0)
return true; return false;
} /// <summary>
/// DataTable转换成实体列表
/// </summary>
/// <typeparam name="T">实体 T </typeparam>
/// <param name="table">datatable</param>
/// <returns></returns>
public static IList<T> DataTableToList<T>(DataTable table)
where T : class
{
if (!IsHaveRows(table))
return new List<T>(); IList<T> list = new List<T>();
T model = default(T);
foreach (DataRow dr in table.Rows)
{
model = Activator.CreateInstance<T>(); foreach (DataColumn dc in dr.Table.Columns)
{
object drValue = dr[dc.ColumnName];
PropertyInfo pi = model.GetType().GetProperty(dc.ColumnName); if (pi != null && pi.CanWrite && (drValue != null && !Convert.IsDBNull(drValue)))
{
pi.SetValue(model, drValue, null);
}
} list.Add(model);
}
return list;
} /// <summary>
/// 实体列表转换成DataTable
/// </summary>
/// <typeparam name="T">实体</typeparam>
/// <param name="list"> 实体列表</param>
/// <returns></returns>
public static DataTable ListToDataTable<T>(IList<T> list)
where T : class
{
if (list == null || list.Count <= 0)
{
return null;
}
DataTable dt = new DataTable(typeof(T).Name);
DataColumn column;
DataRow row; PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); int length = myPropertyInfo.Length;
bool createColumn = true; foreach (T t in list)
{
if (t == null)
{
continue;
} row = dt.NewRow();
for (int i = 0; i < length; i++)
{
PropertyInfo pi = myPropertyInfo[i];
string name = pi.Name;
if (createColumn)
{
column = new DataColumn(name, pi.PropertyType);
dt.Columns.Add(column);
} row[name] = pi.GetValue(t, null);
} if (createColumn)
{
createColumn = false;
} 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, null);
} /// <summary>
/// 将泛型集合类转换成DataTable
/// </summary>
/// <typeparam name="T">集合项类型</typeparam>
/// <param name="list">集合</param>
/// <param name="propertyName">需要返回的列的列名</param>
/// <returns>数据集(表)</returns>
public static DataTable ToDataTable<T>(IList<T> list, params string[] propertyName)
{
List<string> propertyNameList = new List<string>();
if (propertyName != null)
propertyNameList.AddRange(propertyName); DataTable result = new DataTable();
if (list.Count > 0)
{
PropertyInfo[] propertys = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
if (propertyNameList.Count == 0)
{
result.Columns.Add(pi.Name, pi.PropertyType);
}
else
{
if (propertyNameList.Contains(pi.Name))
{
result.Columns.Add(pi.Name, pi.PropertyType);
}
}
} for (int i = 0; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
if (propertyNameList.Count == 0)
{
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>
/// 根据nameList里面的字段创建一个表格,返回该表格的DataTable
/// </summary>
/// <param name="nameList">包含字段信息的列表</param>
/// <returns>DataTable</returns>
public static DataTable CreateTable(List<string> nameList)
{
if (nameList.Count <= 0)
return null; DataTable myDataTable = new DataTable();
myDataTable.TableName = "tableName";//增加一个默认的名字
foreach (string columnName in nameList)
{
myDataTable.Columns.Add(columnName, typeof(string));
}
return myDataTable;
} /// <summary>
/// 通过字符列表创建表字段,字段格式可以是:
/// 1) a,b,c,d,e
/// 2) a|int,b|string,c|bool,d|decimal
/// </summary>
/// <param name="nameString"></param>
/// <returns></returns>
public static DataTable CreateTable(string nameString)
{
string[] nameArray = nameString.Split(new char[] { ',', ';' });
List<string> nameList = new List<string>();
DataTable dt = new DataTable();
dt.TableName = "tableName";//增加一个默认的名字
foreach (string item in nameArray)
{
if (!string.IsNullOrEmpty(item))
{
string[] subItems = item.Split('|');
if (subItems.Length == 2)
{
dt.Columns.Add(subItems[0], ConvertType(subItems[1]));
}
else
{
dt.Columns.Add(subItems[0]);
}
}
}
return dt;
} private static Type ConvertType(string typeName)
{
typeName = typeName.ToLower().Replace("system.", "");
Type newType = typeof(string);
switch (typeName)
{
case "boolean":
case "bool":
newType = typeof(bool);
break;
case "int16":
case "short":
newType = typeof(short);
break;
case "int32":
case "int":
newType = typeof(int);
break;
case "long":
case "int64":
newType = typeof(long);
break;
case "uint16":
case "ushort":
newType = typeof(ushort);
break;
case "uint32":
case "uint":
newType = typeof(uint);
break;
case "uint64":
case "ulong":
newType = typeof(ulong);
break;
case "single":
case "float":
newType = typeof(float);
break; case "string":
newType = typeof(string);
break;
case "guid":
newType = typeof(Guid);
break;
case "decimal":
newType = typeof(decimal);
break;
case "double":
newType = typeof(double);
break;
case "datetime":
newType = typeof(DateTime);
break;
case "byte":
newType = typeof(byte);
break;
case "char":
newType = typeof(char);
break;
}
return newType;
} /// <summary>
/// 获得从DataRowCollection转换成的DataRow数组
/// </summary>
/// <param name="drc">DataRowCollection</param>
/// <returns></returns>
public static DataRow[] GetDataRowArray(DataRowCollection drc)
{
int count = drc.Count;
DataRow[] drs = new DataRow[count];
for (int i = 0; i < count; i++)
{
drs[i] = drc[i];
}
return drs;
} /// <summary>
/// 将DataRow数组转换成DataTable,注意行数组的每个元素须具有相同的数据结构,
/// 否则当有元素长度大于第一个元素时,抛出异常
/// </summary>
/// <param name="rows">行数组</param>
/// <returns></returns>
public static DataTable GetTableFromRows(DataRow[] rows)
{
if (rows.Length <= 0)
{
return new DataTable();
}
DataTable dt = rows[0].Table.Clone();
dt.DefaultView.Sort = rows[0].Table.DefaultView.Sort;
for (int i = 0; i < rows.Length; i++)
{
dt.LoadDataRow(rows[i].ItemArray, true);
}
return dt;
} /// <summary>
/// 排序表的视图
/// </summary>
/// <param name="dt"></param>
/// <param name="sorts"></param>
/// <returns></returns>
public static DataTable SortedTable(DataTable dt, params string[] sorts)
{
if (dt.Rows.Count > 0)
{
string tmp = "";
for (int i = 0; i < sorts.Length; i++)
{
tmp += sorts[i] + ",";
}
dt.DefaultView.Sort = tmp.TrimEnd(',');
}
return dt;
} /// <summary>
/// 根据条件过滤表的内容
/// </summary>
/// <param name="dt"></param>
/// <param name="condition"></param>
/// <returns></returns>
public static DataTable FilterDataTable(DataTable dt, string condition)
{
if (condition.Trim() == "")
{
return dt;
}
else
{
DataTable newdt = new DataTable();
newdt = dt.Clone();
DataRow[] dr = dt.Select(condition);
for (int i = 0; i < dr.Length; i++)
{
newdt.ImportRow((DataRow)dr[i]);
}
return newdt;
}
} /// <summary>
/// 转换.NET的Type到数据库参数的类型
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public static DbType TypeToDbType(Type t)
{
DbType dbt;
try
{
dbt = (DbType)Enum.Parse(typeof(DbType), t.Name);
}
catch
{
dbt = DbType.Object;
}
return dbt;
} /// <summary>
/// 使用分隔符串联表格字段的内容,如:a,b,c
/// </summary>
/// <param name="dt">表格</param>
/// <param name="columnName">字段名称</param>
/// <param name="append">增加的字符串,无则为空</param>
/// <param name="splitChar">分隔符,如逗号(,)</param>
/// <returns></returns>
public static string ConcatColumnValue(DataTable dt, string columnName, string append, char splitChar)
{
string result = append;
if (dt != null && dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
result += string.Format("{0}{1}", splitChar, row[columnName]);
}
}
return result.Trim(splitChar);
} /// <summary>
/// 使用逗号串联表格字段的内容,如:a,b,c
/// </summary>
/// <param name="dt">表格</param>
/// <param name="columnName">字段名称</param>
/// <param name="append">增加的字符串,无则为空</param>
/// <returns></returns>
public static string ConcatColumnValue(DataTable dt, string columnName, string append)
{
string result = append;
if (dt != null && dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
result += string.Format(",{0}", row[columnName]);
}
}
return result.Trim(',');
} /// <summary>
/// 判断表格是否包含指定的全部字段名称,如果其中一个不符合则返回false
/// </summary>
/// <param name="dt">表格对象</param>
/// <param name="columnString">字段列名称,逗号分开</param>
/// <returns></returns>
public static bool ContainAllColumns(DataTable dt, string columnString)
{
bool result = true;
if (dt != null && !string.IsNullOrEmpty(columnString))
{
List<string> columnList = columnString.Split(',').ToList();
foreach (string columnName in columnList)
{
if (!string.IsNullOrEmpty(columnName) && !dt.Columns.Contains(columnName))
{
result = false;
}
}
}
else
{
result = false;
}
return result;
}
}
DataTableHelper的更多相关文章
- DataTable操作工具类DataTableHelper
DataTable操作工具类DataTableHelper. 功能介绍: 将泛型集合填充为数据表 将泛型填充为数据表 将对象集合填充为数据表 将对象填充为数据表 将定IDictionary数据转换为D ...
- DataTableHelper.cs 将DataTable转换为List,将List转换为DataTable的实现类
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...
- 从零开始编写自己的C#框架(21)——添加分类类型页面
页面权限与页面控件权限经过简单的调试后,终于启用起来了,以后大家添加新页面时,就必须按照本章介绍的方法,将你新增的页面注册到系统中,这样才能访问与进行相关操作. 下面讲讲如何创建一个分类类型的页面. ...
- 从零开始编写自己的C#框架(17)——Web层后端首页
后端首页是管理员登陆后进入的第一个页面,主要是显示当前登陆用户信息.在线人数.菜单树列表.相关功能按键和系统介绍.让管理员能更方便的找到息想要的内容. 根据不同系统的需要,首页会显示不同的内容,比如显 ...
- 从零开始编写自己的C#框架(14)——T4模板在逻辑层中的应用(三)
原本关于T4模板原想分5个章节详细解说的,不过因为最近比较忙,也不想将整个系列时间拉得太长,所以就将它们整合在一块了,可能会有很多细节没有讲到,希望大家自己对着代码与模板去研究. 本章代码量会比较大, ...
- 文字处理控件TX Text Control的使用
这几天一直在研究TX Text Control的使用,由于这方面的资料相对比较少,主要靠下载版本的案例代码进行研究,以及官方的一些博客案例进行学习,使用总结了一些心得,特将其总结出来,供大家分享学习. ...
- Join two DataTables in C#
var query = (from x in a.AsEnumerable() join y in b.AsEnumerable() on x.Field<int>("col1& ...
- 面向对象架构模式之:领域模型(Domain Model)
一:面向对象设计中最简单的部分与最难的部分 如果说事务脚本是 面向过程 的,那么领域模型就是 面向对象 的.面向对象的一个很重要的点就是:“把事情交给最适合的类去做”,即:“你得在一个个领域类之间跳转 ...
- 基于MVC4+EasyUI的Web开发框架经验总结(10)--在Web界面上实现数据的导入和导出
数据的导入导出,在很多系统里面都比较常见,这个导入导出的操作,在Winform里面比较容易实现,我曾经在之前的一篇文章<Winform开发框架之通用数据导入导出操作>介绍了在Winform ...
随机推荐
- Linux下MySQL远程链接配置
配置步骤: 1).首先进入数据库,使用系统数据库mysql mysql -u root -p mysql 2).接着对系统数据库的root账户设置远程访问的密码,与本地的root访问密码并不冲突 gr ...
- 大数据自学5-Python操作Hbase
在Hue环境中本身是可以直接操作Hbase数据库的,但是公司的环境不知道什么原因一直提示"Api Error:timed out",进度条一直在跑,却显示不出表. 但是在CDH后台 ...
- sql server 触发器的简单用法
触发器 -- 一下写的都是我对触发器的理解 当在执行insert . delete . 等操作的时候 随便要做一些额外的操作, 比如在添加的时候就会将新添加的数据存到inserted表中 写个实例 ...
- webVR框架A-frame
A-frame:https://blog.csdn.net/sun124608666/article/details/77869570 three.js学习文档:http://www.hewebgl. ...
- 处理jquery的ajax请求session过期跳转到登录页面
首先需要在拦截器中判断是否是ajax请求,如果是 if(isAjaxRequest(request)){//ajax请求 response.setHeader("sessionstatus& ...
- Django form choices, placeholder
item=CharField(max_length=20,min_length=1,required=True,widget=widgets.TextInput({'placeholder':'tes ...
- python之auto鼠标/键盘事件
mouse_key.py import os import time import win32gui import win32api import win32con from ctypes impor ...
- DDoS防御方案
转自:http://netsecurity.51cto.com/art/201211/368930.htm 深入浅出DDoS攻击防御应对篇:DDoS防御方案 谈到DDoS防御,首先就是要知道到底遭受了 ...
- k8s debug
https://feisky.gitbooks.io/kubernetes/components/api-aggregation.html API convention Kubernetes deep ...
- 零基础Python爬虫实现(爬取最新电影排行)
提示:本学习来自Ehco前辈的文章, 经过实现得出的笔记. 目标网站 http://dianying.2345.com/top/ 网站结构 要爬的部分,在ul标签下(包括li标签), 大致来说迭代li ...