datatable转换成list集合
public static T TableToEntity<T>(DataTable dt, int rowindex = 0, bool isStoreDB = true)
{
Type type = typeof(T);
T entity = Activator.CreateInstance<T>();
if (dt == null)
{
return entity;
}
DataRow row = dt.Rows[rowindex];
PropertyInfo[] pArray = type.GetProperties();
foreach (PropertyInfo p in pArray)
{
if (!dt.Columns.Contains(p.Name) || row[p.Name] == null || row[p.Name] == DBNull.Value)
{
continue;
}
if (isStoreDB && p.PropertyType == typeof(DateTime) && Convert.ToDateTime(row[p.Name]) < Convert.ToDateTime("1753-01-02"))
{
continue;
}
try
{
var obj = Convert.ChangeType(row[p.Name], p.PropertyType);
p.SetValue(entity, obj, null);
}
catch (Exception)
{
}
}
return entity;
}
//多行datatable数据转换为对象:文章来源:https://www.toymoban.com/news/detail-614711.html
public static List<T> TableToList<T>(DataTable dt)
{
List<T> listT = new List<T>();
Type type = typeof(T);
if (dt == null)
{
return listT;
}
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
T entity = Activator.CreateInstance<T>();
DataRow row = dt.Rows[i];
PropertyInfo[] pArray = type.GetProperties();
foreach (PropertyInfo p in pArray)
{
if (!dt.Columns.Contains(p.Name) || row[p.Name] == null || row[p.Name] == DBNull.Value)
{
continue;
}
if (p.PropertyType == typeof(DateTime) && Convert.ToDateTime(row[p.Name]) < Convert.ToDateTime("1753-01-02"))
{
continue;
}
try
{
var obj = Convert.ChangeType(row[p.Name], p.PropertyType);
p.SetValue(entity, obj, null);
}
catch (Exception)
{
// throw;
}
}
listT.Add(entity);
}
}
return listT;
}
datatable转换成json文章来源地址https://www.toymoban.com/news/detail-614711.html
public static string DataTableToJson(DataTable table)
{
var JsonString = new StringBuilder();
if (table==null)
{
return "数据内容为null";
}
if (table.Rows.Count > 0 && table!=null)
{
JsonString.Append("[");
for (int i = 0; i < table.Rows.Count; i++)
{
JsonString.Append("{");
for (int j = 0; j < table.Columns.Count; j++)
{
if (j < table.Columns.Count - 1)
{
JsonString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\",");
}
else if (j == table.Columns.Count - 1)
{
JsonString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\"");
}
}
if (i == table.Rows.Count - 1)
{
JsonString.Append("}");
}
else
{
JsonString.Append("},");
}
}
JsonString.Append("]");
}
return JsonString.ToString();
}
到了这里,关于dataTable转成对象、json、list的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!