Created
July 1, 2014 02:18
-
-
Save shengoo/b015bce4702602594610 to your computer and use it in GitHub Desktop.
DataTableSerializer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DataTableSerializer | |
{ | |
public static List<T> ToList<T>(DataTable dt) | |
{ | |
var list = new List<T>(); | |
if (dt == null || dt.Rows.Count == 0) | |
return list;//return empty list instead of null object | |
list.AddRange(from DataRow row in dt.Rows select ToEntity<T>(row)); | |
return list; | |
} | |
public static T ToEntity<T>( DataRow row) | |
{ | |
var objType = typeof(T); | |
var obj = Activator.CreateInstance<T>(); | |
foreach (DataColumn column in row.Table.Columns) | |
{ | |
var property = objType.GetProperty(column.ColumnName, | |
BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); | |
if (property == null || !property.CanWrite) | |
{ | |
continue; | |
} | |
var value = row[column.ColumnName]; | |
if (value == DBNull.Value) | |
{ | |
value = null; | |
} | |
else | |
{ | |
//add what you need. | |
//if (column.DataType == typeof (DateTime)) | |
//{ | |
// value = ((DateTime)value).ToString("yyyy-MM-dd"); | |
//} | |
} | |
property.SetValue(obj, value, null); | |
} | |
return obj; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment