namespace ChatRoom.Services.Utils
{
public static class ConvertUtils
{
/// <summary>
/// 提供将DataTable类型对象转换为List集合
/// </summary>
/// <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)
{
properties[j].SetValue(type, currentRow[i], null);
}
}
}
list.Add(type);
type = new T();
}
}
else
{
list = null;
}
}
else
{
throw new ArgumentNullException("参数不能为空");
}
return list;
}
}
}
不知效率性能如何啊??