DataTable转换到List
方法一:
public static IList<T> ConvertTo<T>(DataTable table)
{
if (table == null)
{
return null;
}
List<DataRow> rows = new List<DataRow>();
foreach (DataRow row in table.Rows)
{
rows.Add(row);
}
return ConvertTo<T>(rows);
}
public static IList<T> ConvertTo<T>(IList<DataRow> rows)
{
IList<T> list = null;
if (rows != null)
{
list = new List<T>();
foreach (DataRow row in rows)
{
T item = CreateItem<T>(row);
list.Add(item);
}
}
return list;
}
public static T CreateItem<T>(DataRow row)
{
T obj = default(T);
if (row != null)
{
obj = Activator.CreateInstance<T>();
foreach (DataColumn column in row.Table.Columns)
{
PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);
try
{
object value = row[column.ColumnName];
prop.SetValue(obj, value, null);
}
catch
{ //You can log something here
//throw;
}
}
}
return obj;
}
*************************************
/// </summary>
/// <param name="Json"></param>
/// <returns></returns>
public static object ToJson(this string Json)
{
return JsonConvert.DeserializeObject(Json);
}
public static string ToJson(this object obj)
{
IsoDateTimeConverter idtc = new IsoDateTimeConverter();
idtc.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
JsonSerializerSettings jsonSettings = new JsonSerializerSettings
{
};
jsonSettings.Converters.Add(idtc);
return JsonConvert.SerializeObject(obj, jsonSettings);
}