1 static DataTable ConvertJsonToTable(string jsonValue)
2 {
3 DataTable dt = (DataTable)JsonConvert.DeserializeObject(jsonValue, typeof(DataTable));
4 return dt;
5 }
static DataTable ConvertListToDataTable<T>(List<T> dataList)
{
DataTable dt = new DataTable();
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
for(int i=0;i<props.Count;i++)
{
PropertyDescriptor prop = props[i];
dt.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach(T item in dataList)
{
for(int i=0;i<values.Length;i++)
{
values[i] = props[i].GetValue(item);
}
dt.Rows.Add(values);
}
return dt;
}
static DataTable ConvertTToDT<T>(List<T> dataList)
{
if(dataList==null || !dataList.Any())
{
return null;
}
DataTable dt = new DataTable();
PropertyInfo[] pis = typeof(T).GetProperties();
for(int i=0;i<pis.Count();i++)
{
dt.Columns.Add(pis[i].Name, pis[i].PropertyType);
}
object[] valuesArr = new object[pis.Count()];
foreach(var data in dataList)
{
for(int i=0;i<pis.Count();i++)
{
valuesArr[i] = pis[i].GetValue(data);
}
dt.Rows.Add(valuesArr);
}
return dt;
}
来源:oschina
链接:https://my.oschina.net/u/4261744/blog/3316115