Browse Source

Add List to DataTable

pull/1/head
skx 4 years ago
parent
commit
2fbd77ed74
  1. 31
      Src/Asp.Net/SqlSugar/Infrastructure/ContextMethods.cs
  2. 1
      Src/Asp.Net/SqlSugar/Interface/IContextMethods.cs

31
Src/Asp.Net/SqlSugar/Infrastructure/ContextMethods.cs

@ -536,6 +536,37 @@ namespace SqlSugar
} }
return this.DeserializeObject<List<T>>(this.SerializeObject(deserializeObject)); return this.DeserializeObject<List<T>>(this.SerializeObject(deserializeObject));
} }
public DataTable ListToDataTable<T>(List<T> list)
{
DataTable result = new DataTable();
if (list.Count > 0)
{
PropertyInfo[] propertys = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
//获取类型
Type colType = pi.PropertyType;
//当类型为Nullable<>时
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
result.Columns.Add(pi.Name, colType);
}
for (int i = 0; i < list.Count; i++)
{
ArrayList tempList = new ArrayList();
foreach (PropertyInfo pi in propertys)
{
object obj = pi.GetValue(list[i], null);
tempList.Add(obj);
}
object[] array = tempList.ToArray();
result.LoadDataRow(array, true);
}
}
return result;
}
public Dictionary<string, object> DataTableToDictionary(DataTable table) public Dictionary<string, object> DataTableToDictionary(DataTable table)
{ {
return table.Rows.Cast<DataRow>().ToDictionary(x => x[0].ToString(), x => x[1]); return table.Rows.Cast<DataRow>().ToDictionary(x => x[0].ToString(), x => x[1]);

1
Src/Asp.Net/SqlSugar/Interface/IContextMethods.cs

@ -27,6 +27,7 @@ namespace SqlSugar
SqlSugarProvider CopyContext(bool isCopyEvents = false); SqlSugarProvider CopyContext(bool isCopyEvents = false);
dynamic DataTableToDynamic(DataTable table); dynamic DataTableToDynamic(DataTable table);
List<T> DataTableToList<T>(DataTable table); List<T> DataTableToList<T>(DataTable table);
DataTable ListToDataTable<T>(List<T> list);
Dictionary<string, object> DataTableToDictionary(DataTable table); Dictionary<string, object> DataTableToDictionary(DataTable table);
ICacheService GetReflectionInoCacheInstance(); ICacheService GetReflectionInoCacheInstance();
void RemoveCacheAll(); void RemoveCacheAll();

Loading…
Cancel
Save