DataSetToList 和 DataTableTolist 转换
DataSetToList 及DataTableTolist经常使用,在此分享一下我的方法。
1、DataSetToList
1 /// <summary> 2 /// DataSetToList 3 /// </summary> 4 /// <typeparam name="T">转换类型</typeparam> 5 /// <param name="dataSet">数据源</param> 6 /// <param name="tableIndex">需要转换表的索引</param> 7 /// /// <returns>泛型集合</returns> 8 public static List<T> DataSetToList<T>(DataSet dataset, int tableIndex) 9 { 10 //确认参数有效 11 if (dataset == null || dataset.Tables.Count <= 0 || tableIndex < 0) 12 { 13 return null; 14 } 15 16 DataTable dt = dataset.Tables[tableIndex]; 17 18 List<T> list = new List<T>(); 19 20 21 for (int i = 0; i < dt.Rows.Count; i++) 22 { 23 //创建泛型对象 24 T _t = Activator.CreateInstance<T>(); 25 26 //获取对象所有属性 27 PropertyInfo[] propertyInfo = _t.GetType().GetProperties(); 28 29 //属性和名称相同时则赋值 30 for (int j = 0; j < dt.Columns.Count; j++) 31 { 32 foreach (PropertyInfo info in propertyInfo) 33 { 34 if (dt.Columns[j].ColumnName.ToUpper().Equals(info.Name.ToUpper())) 35 { 36 if (dt.Rows[i][j] != DBNull.Value) 37 { 38 info.SetValue(_t, dt.Rows[i][j], null); 39 } 40 else 41 { 42 info.SetValue(_t, null, null); 43 } 44 45 break; 46 } 47 } 48 } 49 50 list.Add(_t); 51 } 52 53 return list; 54 }
2、DataTableToList
/// <summary>
/// 将DataTalbe 转为List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <returns></returns>
public static List<T> ConvertToList<T>(DataTable table) where T : new()
{
List<T> list = null;
if (table != null)
{
DataColumnCollection columns = table.Columns;
int columnCount = columns.Count;
T type = new T();
Type columnType = type.GetType();
PropertyInfo[] properties = columnType.GetProperties();
if (properties.Length == columnCount)
{
list = new List<T>();
foreach (DataRow currentRow in table.Rows)
{
for (int i = 0; i < columnCount; i++)
{
for (int j = 0; j < properties.Length; j++)
{
if (columns[i].ColumnName == properties[j].Name)
{
if (currentRow[i] != DBNull.Value)
{
properties[j].SetValue(type, currentRow[i], null);
}
}
}
}
list.Add(type); type = new T();
}
}
else { list = null; }
}
else
{
throw new ArgumentNullException("参数不能为空");
}
return list;
}
}