c# DataTable轉集合、集合轉DataTable、物件轉JSON、JSON轉物件
1.DataTable轉集合
public class ModelConvertHelper<T> where T : new()
{
public static IList<T> ConvertToModel(DataTable dt)
{
IList<T> ts = new List<T>();
Type type = typeof(T);
string tempName = "";
foreach (DataRow dr in dt.Rows)
{
T t = new T();
// 獲得此模型的公共屬性
PropertyInfo[] propertys = t.GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
tempName = pi.Name; // 檢查DataTable是否包含此列
if (dt.Columns.Contains(tempName))
{
// 判斷此屬性是否有Setter
if (!pi.CanWrite) continue;
object value = dr[tempName];
if (value != DBNull.Value)
pi.SetValue(t, value, null);
}
}
ts.Add(t);
}
return ts;
}
}
// 使用示例: (List<Product>)ModelConvertHelper<Product>.ConvertToModel(dt);
2.集合轉DataTable
public static DataSet ListToDataTable(IList list)
{
DataTable result = new DataTable();
if (list.Count > 0)
{
PropertyInfo[] propertys = list[0].GetType().GetProperties();
foreach (PropertyInfo pi in propertys)
{
result.Columns.Add(pi.Name, pi.PropertyType);
}
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);
}
}
DataSet ds = new DataSet();
ds.Tables.Add(result.Copy());
return ds;
}
3.物件轉JSON
public static string ToJson(this object obj)
{
return JsonConvert.SerializeObject(obj);
}
4.JSON轉物件
public static T ToObject<T>(this object obj)
{
return JsonConvert.DeserializeObject<T>(obj.ToString());
}