Below is the Public extension method which will convert datatable to LIST<T>
public static IList<T> ConvertToList<T>(this DataTable dt) where T : class, new() { if (dt == null || dt.Rows.Count == 0) return null; IList<T> list = new List<T>(); foreach (DataRow row in dt.Rows) { T obj = ConvertDataRowToEntity<T>(row); list.Add(obj); } return list; } |
This method will internally called below method
private static T ConvertDataRowToEntity<T>(DataRow row) where T : class, new() { Type objType = typeof(T); T obj = Activator.CreateInstance<T>(); foreach (DataColumn column in row.Table.Columns) { PropertyInfo property = objType.GetProperty(column.ColumnName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); if (property == null || !property.CanWrite) { continue; } object value = row[column.ColumnName]; if (value == DBNull.Value) value = null; property.SetValue(obj, value, null); Debug.WriteLine("obj." + property.Name + " = row[\"" + column.ColumnName +"\"];"); } return obj; } |
No comments:
Post a Comment