using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; namespace Base { public class BaseClass { //DataSet转换为List /// <summary> /// DataSet转换为List /// </summary> /// <typeparam name="T">模板</typeparam> /// <param name="dataSet">待转换数据</param> /// <returns>转换后数据</returns> public static List<T> ConvertToList<T>(DataTable dataTable) { List<T> buffer = new List<T>(); // 遍历所有行 for (int i = 0; i < dataTable.Rows.Count; i++) { DataRow row = dataTable.Rows[i]; T t = Activator.CreateInstance<T>(); // 遍历所属性 foreach (System.Reflection.PropertyInfo property in typeof(T).GetProperties()) { // 该属性包含在集合中 if (dataTable.Columns.Contains(property.Name) && !property.Name.Equals("Id")) { // 该属性值不是空 if (row[property.Name] != DBNull.Value && row[property.Name] != null) { // 整型 if (property.PropertyType.Equals(typeof(int))) { property.SetValue(t, Convert.ToInt32(row[property.Name]), null); } else if (property.PropertyType == typeof(double)) { property.SetValue(t, Convert.ToDouble(row[property.Name]), null); } else if (property.PropertyType.Equals(typeof(string))) { property.SetValue(t, row[property.Name].ToString(), null); } else if (property.PropertyType.Equals(typeof(DateTime))) { property.SetValue(t, Convert.ToDateTime(row[property.Name]), null); } else { property.SetValue(t, row[property.Name], null); } } } } buffer.Add(t); } return buffer; } } } |
|