. NET infrastructure method-DataTableToList common method, datatabletolist
Basic Method of. NET architecture-DataTableToList common method we often need to return the data read from the database as a DataTable type, and often need to traverse the DataTable to convert to List> T <. We often need to write a method suitable for their database architecture for each able to be converted to a List. The code below:
public static class DataTableTools<T> where T : class, new() { public static List<T> DataTableToList(DataTable dt) { List<T> list = null; var rowCount = dt.Rows.Count; if (rowCount > 0) { list = new List<T>(); int i; for (i = 0; i < rowCount; i++) { T model = DataRowToModel(dt.Rows[i]); list.Add(model); } } return list; } private static T DataRowToModel(DataRow dr) { T model = new T(); var propertiesCount = typeof(T).GetProperties().Length; for (int j = 0; j < propertiesCount; j++) { PropertyInfo propertyInfo = GetModelPropertyInfo(model, dr.Table.Columns[j]); if (propertyInfo != null && dr[j] != DBNull.Value) { propertyInfo.SetValue(model, dr[j]); } } return model; } private static PropertyInfo GetModelPropertyInfo(T model, DataColumn column) { string propertyName = column.ColumnName; return model.GetType().GetProperty(propertyName); } }
The Code also needs to traverse the able to convert each row of DataRow in the DataTable into a T-type Model. Here, we obtain the ColumnName of each column of the row based on the data architecture of each row. Based on this ColumnName, we can obtain the attributes of generic T-GetModelPropertyInfo () method, and set the attribute value of this model through SetValue. It is also the use of the column attribute name of the row data architecture to obtain the attributes of the generic T,
Therefore, make sure that the attribute name of the generic T is the same as that of the data architecture, and this general method can be used only in this way.I believe that you have mastered this method. If you have any suggestions, please kindly advise. If you have learned this, please like yourself and me.