public static class DataTableExtensions
{
public static List<T> ToList<T>(this DataTable dt) where T : new()
{
var list = new List<T>();
if (dt == null) return list;
var len = dt.Rows.Count;
for (var i = 0; i < len; i++)
{
var info = new T();
foreach (DataColumn dc in dt.Rows[i].Table.Columns)
{
var field = dc.ColumnName;
var value = dt.Rows[i][field].ToString();
if (string.IsNullOrEmpty(value)) continue;
if (IsDate(value))
{
value = DateTime.Parse(value).ToString();
}
var p = info.GetType().GetProperty(field);
try
{
if (p.PropertyType == typeof(string))
{
p.SetValue(info, value, null);
}
else if (p.PropertyType == typeof(int))
{
p.SetValue(info, int.Parse(value), null);
}
else if (p.PropertyType == typeof(bool))
{
p.SetValue(info, bool.Parse(value), null);
}
else if (p.PropertyType == typeof(DateTime))
{
p.SetValue(info, DateTime.Parse(value), null);
}
else if (p.PropertyType == typeof(float))
{
p.SetValue(info, float.Parse(value), null);
}
else if (p.PropertyType == typeof(double))
{
p.SetValue(info, double.Parse(value), null);
}
else
{
p.SetValue(info, value, null);
}
}
catch (Exception)
{
//p.SetValue(info, ex.Message, null);
}
}
list.Add(info);
}
dt.Dispose(); dt = null;
return list;
}
/// <summary>
/// 按照属性顺序的列名集合
/// </summary>
public static IList<string> GetColumnNames(this DataTable dt)
{
DataColumnCollection dcc = dt.Columns;
//由于集合中的元素是确定的,所以可以指定元素的个数,系统就不会分配多余的空间,效率会高点
IList<string> list = new List<string>(dcc.Count);
foreach (DataColumn dc in dcc)
{
list.Add(dc.ColumnName);
}
return list;
}
private static bool IsDate(string d)
{
DateTime d1;
double d2;
return !double.TryParse(d, out d2) && DateTime.TryParse(d, out d1);
}
}