using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Text;
namespace Core.Util
{
public static partial class Extention
{
public static List<T> ToList<T>(this DataTable dt)
{
List<T> list = new List<T>();
if (dt == null)
return list;
else if (dt.Rows.Count == 0)
return list;
Dictionary<string, string> dicField = new Dictionary<string, string>();
Dictionary<string, string> dicProperty = new Dictionary<string, string>();
Type type = typeof(T);
type.GetFields().ForEach(aFiled =>
{
dicField.Add(aFiled.Name.ToLower(), aFiled.Name);
});
type.GetProperties().ForEach(aProperty =>
{
dicProperty.Add(aProperty.Name.ToLower(), aProperty.Name);
});
for (int i = 0; i < dt.Rows.Count; i++)
{
T _t = Activator.CreateInstance<T>();
for (int j = 0; j < dt.Columns.Count; j++)
{
string memberKey = dt.Columns[j].ColumnName.ToLower();
if (dicField.ContainsKey(memberKey))
{
FieldInfo theField = type.GetField(dicField[memberKey]);
var dbValue = dt.Rows[i][j];
if (dbValue.GetType() == typeof(DBNull))
dbValue = null;
if (dbValue != null)
{
Type memberType = theField.FieldType;
dbValue = dbValue.ChangeType_ByConvert(memberType);
}
theField.SetValue(_t, dbValue);
}
if (dicProperty.ContainsKey(memberKey))
{
PropertyInfo theProperty = type.GetProperty(dicProperty[memberKey]);
var dbValue = dt.Rows[i][j];
if (dbValue.GetType() == typeof(DBNull))
dbValue = null;
if (dbValue != null)
{
Type memberType = theProperty.PropertyType;
dbValue = dbValue.ChangeType_ByConvert(memberType);
}
theProperty.SetValue(_t, dbValue);
}
}
list.Add(_t);
}
return list;
}
public static string ToCsvStr(this DataTable dt)
{
StringBuilder sb = new StringBuilder();
DataColumn colum;
foreach (DataRow row in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
colum = dt.Columns[i];
if (i != 0) sb.Append(",");
if (colum.DataType == typeof(string) && row[colum].ToString().Contains(","))
{
sb.Append("\"" + row[colum].ToString().Replace("\"", "\"\"") + "\"");
}
else sb.Append(row[colum].ToString());
}
sb.AppendLine();
}
return sb.ToString();
}
}
}