DataSetToList 及DataTableTolist经常使用,在此分享一下我的方法。
1、DataSetToList
/// <summary>
/// DataSetToList
/// </summary>
/// <typeparam name="T">转换类型</typeparam>
/// <param name="dataSet">数据源</param>
/// <param name="tableIndex">需要转换表的索引</param>
/// /// <returns>泛型集合</returns>
public static List<T> DataSetToList<T>(DataSet dataset, int tableIndex)
{
//确认参数有效
if (dataset == null || dataset.Tables.Count <= || tableIndex < )
{
return null;
} DataTable dt = dataset.Tables[tableIndex]; List<T> list = new List<T>(); for (int i = ; i < dt.Rows.Count; i++)
{
//创建泛型对象
T _t = Activator.CreateInstance<T>(); //获取对象所有属性
PropertyInfo[] propertyInfo = _t.GetType().GetProperties(); //属性和名称相同时则赋值
for (int j = ; j < dt.Columns.Count; j++)
{
foreach (PropertyInfo info in propertyInfo)
{
if (dt.Columns[j].ColumnName.ToUpper().Equals(info.Name.ToUpper()))
{
if (dt.Rows[i][j] != DBNull.Value)
{
info.SetValue(_t, dt.Rows[i][j], null);
}
else
{
info.SetValue(_t, null, null);
} break;
}
}
} list.Add(_t);
} return list;
}
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;
}
}