Basf_TCC7/HJGL/FineUIPro.Web/common/DataTableEx.cs

288 lines
8.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;
/// <summary>
/// DataTableEx 的摘要说明
/// </summary>
public static class DataTableEx
{
public static List<T> ToList<T>(this DataTable dt) where T : new()
{
List<T> ts = new List<T>();
foreach (DataRow dr in dt.Rows)
{
T t = new T();
foreach (var c in dt.Columns)
{
object value = dr[c.ToString()];
if (value != DBNull.Value)
{
var p = t.GetType().GetProperty(c.ToString());
if (p != null)
{
p.SetValue(t, ConvertHelper.ChangeType(value, p.PropertyType), null);
}
}
}
ts.Add(t);
}
return ts;
}
public static List<T> ConvertTo<T>(DataTable datatable) where T : new()
{
var temp = new List<T>();
try
{
var columnsNames = (from DataColumn dataColumn in datatable.Columns select dataColumn.ColumnName).ToList();
temp = datatable.AsEnumerable().ToList().ConvertAll<T>(row => GetObject<T>(row, columnsNames));
return temp;
}
catch
{
return temp;
}
}
private static T GetObject<T>(DataRow row, List<string> columnsName) where T : new()
{
T obj = new T();
try
{
string columnname = "";
PropertyInfo[] Properties = typeof(T).GetProperties();
foreach (PropertyInfo objProperty in Properties)
{
columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());
if (!string.IsNullOrEmpty(columnname))
{
var value = row[columnname];
if (!string.IsNullOrEmpty(value.ToString()))
{
Type type;
type = Nullable.GetUnderlyingType(objProperty.PropertyType) ?? objProperty.PropertyType;
objProperty.SetValue(obj,
type == value.GetType()
? Convert.ChangeType(value, type)
: System.Enum.ToObject(type, value), null);
}
}
}
return obj;
}
catch (Exception exception)
{
return obj;
}
}
/// <summary>
/// 单字段值
/// </summary>
/// <returns></returns>
public static List<string> ToList(this DataTable dt)
{
List<string> ts = new List<string>();
foreach (DataRow dr in dt.Rows)
{
foreach (var c in dt.Columns)
{
object value = dr[c.ToString()];
if (value != DBNull.Value)
{
ts.Add(value.ToString());
}
}
}
return ts;
}
public static T ToData<T>(this DataTable dt) where T : new()
{
if (dt.Rows.Count > 1)
{
throw new Exception("");
}
List<T> ts = new List<T>();
foreach (DataRow dr in dt.Rows)
{
T t = new T();
foreach (var c in dt.Columns)
{
object value = dr[c.ToString()];
if (value != DBNull.Value)
{
var p = t.GetType().GetProperty(c.ToString());
if (p != null)
{
p.SetValue(t, ConvertHelper.ChangeType(value, p.PropertyType), null);
}
}
}
return t;
}
return default(T);
}
public static void FillData<T>(this DataTable dt, ref T t) where T : new()
{
if (dt.Rows.Count > 1)
{
throw new Exception("");
}
foreach (DataRow dr in dt.Rows)
{
foreach (var c in dt.Columns)
{
object value = dr[c.ToString()];
if (value != DBNull.Value)
{
var p = t.GetType().GetProperty(c.ToString());
if (p != null)
{
p.SetValue(t, ConvertHelper.ChangeType(value, p.PropertyType), null);
}
}
}
}
}
/// <summary>
/// list转化为table
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entitys"></param>
/// <returns></returns>
public static DataTable ListToDataTable<T>(List<T> entitys)
{
//检查实体集合不能为空
if (entitys == null || entitys.Count < 1)
{
return new DataTable();
}
//取出第一个实体的所有Propertie
Type entityType = entitys[0].GetType();
PropertyInfo[] entityProperties = entityType.GetProperties();
//生成DataTable的structure
//生产代码中应将生成的DataTable结构Cache起来此处略
DataTable dt = new DataTable("dt");
for (int i = 0; i < entityProperties.Length; i++)
{
//dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType);
dt.Columns.Add(entityProperties[i].Name);
}
//将所有entity添加到DataTable中
foreach (object entity in entitys)
{
//检查所有的的实体都为同一类型
if (entity.GetType() != entityType)
{
throw new Exception("要转换的集合元素类型不一致");
}
object[] entityValues = new object[entityProperties.Length];
for (int i = 0; i < entityProperties.Length; i++)
{
entityValues[i] = entityProperties[i].GetValue(entity, null);
}
dt.Rows.Add(entityValues);
}
return dt;
}
/// <summary>
/// 查询指定条数分页
/// </summary>
/// <returns></returns>
public static DataTable GetPageToTable(DataTable dt, int StartNum, int EndNum)
{
//0页代表每页数据直接返回
if (EndNum == 0) return dt;
//数据源为空返回空DataTable
if (dt == null) return new DataTable();
DataTable newdt = dt.Copy();
newdt.Clear();//copy dt的框架
if (StartNum >= dt.Rows.Count)
return newdt;//源数据记录数小于等于要显示的记录直接返回dt
if (EndNum > dt.Rows.Count)
EndNum = dt.Rows.Count;
for (int i = StartNum; i <= EndNum - 1; i++)
{
DataRow newdr = newdt.NewRow();
DataRow dr = dt.Rows[i];
foreach (DataColumn column in dt.Columns)
{
newdr[column.ColumnName] = dr[column.ColumnName];
}
newdt.Rows.Add(newdr);
}
return newdt;
}
}
public static class ConvertHelper
{
public static object ChangeType(object obj, Type conversionType)
{
return ChangeType(obj, conversionType, System.Threading.Thread.CurrentThread.CurrentCulture);
}
public static object ChangeType(object obj, Type conversionType, IFormatProvider provider)
{
#region Nullable
Type nullableType = Nullable.GetUnderlyingType(conversionType);
if (nullableType != null)
{
if (obj == null)
{
return null;
}
return Convert.ChangeType(obj, nullableType, provider);
}
#endregion
if (typeof(System.Enum).IsAssignableFrom(conversionType))
{
return Enum.Parse(conversionType, obj.ToString());
}
return Convert.ChangeType(obj, conversionType, provider);
}
/// <summary>
/// 分页
/// </summary>
/// <returns></returns>
public static List<T> PageList<T>(List<T> list, out int total, int pageIndex = 1, int pageSize = 10)
{
pageIndex = pageIndex - 1;
total = 0;
if (list == null || list.Count == 0)
return list;
total = list.Count;
int startIndex = pageIndex * pageSize;
if (startIndex + pageSize > list.Count)
{
pageSize = list.Count - startIndex;
}
if (pageSize <= 0) return new List<T>();
return list.GetRange(startIndex, pageSize);
}
}