DataTable和List相互转换
DataTable转换到List
方法一
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| public static IList<T> ConvertTo<T>(DataTable table) { if (table == null) { return null; } List<DataRow> rows = new List<DataRow>(); foreach (DataRow row in table.Rows) { rows.Add(row); } return ConvertTo<T>(rows); } public static IList<T> ConvertTo<T>(IList<DataRow> rows) { IList<T> list = null; if (rows != null) { list = new List<T>(); foreach (DataRow row in rows) { T item = CreateItem<T>(row); list.Add(item); } } return list; } public static T CreateItem<T>(DataRow row) { T obj = default(T); if (row != null) { obj = Activator.CreateInstance<T>(); foreach (DataColumn column in row.Table.Columns) { PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName); try { object value = row[column.ColumnName]; prop.SetValue(obj, value, null); } catch { } } } return obj; }
|
方法二
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
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; if (dt.Columns.Contains(tempName)) { if (!pi.CanWrite) continue; object value = dr[tempName]; if (value != DBNull.Value) pi.SetValue(t, value, null); } } ts.Add(t); } return ts; } }
|
使用方式:
// 获得查询结果
DataTable dt = DbHelper.ExecuteDataTable(…);
// 把DataTable转换为IList
IList users = ModelConvertHelper.ConvertToModel(dt);
List/IEnumerable转换到DataTable/DataView
方法一
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
private DataTable ToDataTable<T>(List<T> items) { var tb = new DataTable(typeof (T).Name); PropertyInfo[] props = typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in props) { Type t = GetCoreType(prop.PropertyType); tb.Columns.Add(prop.Name, t); } foreach (T item in items) { var values = new object[props.Length]; for (int i = 0; i < props.Length; i++) { values[i] = props[i].GetValue(item, null); } tb.Rows.Add(values); } return tb; }
public static bool IsNullable(Type t) { return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)); }
public static Type GetCoreType(Type t) { if (t != null && IsNullable(t)) { if (!t.IsValueType) { return t; } else { return Nullable.GetUnderlyingType(t); } } else { return t; } }
|
方法二
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public static DataTable ToDataTable<T>(IEnumerable<T> collection) { var props = typeof(T).GetProperties(); var dt = new DataTable(); dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray()); if (collection.Count() > 0) { for (int i = 0; i < collection.Count(); i++) { ArrayList tempList = new ArrayList(); foreach (PropertyInfo pi in props) { object obj = pi.GetValue(collection.ElementAt(i), null); tempList.Add(obj); } object[] array = tempList.ToArray(); dt.LoadDataRow(array, true); } } return dt; }
|
DataTable转换成Json
方法1:使用StringBuilder
这是Json样本数据的样子: {“姓名 “:”张三”, “年龄”:”30”}。Json里用花括号保存对象,它可以包含多个名称/值对。所以使用StringBuilder我们可以创建一个类似的Json字符串。
由于要使用StringBuilder类,我们首先需要导入System.Text命名空间,如下:
下面的代码将生成一个Json字符串,遍历DataTable的行和列,获取数据,添加到一个StringBuilder对象 JsonString,然后返回这个对象。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| public string DataTableToJson(DataTable table) { var JsonString = new StringBuilder(); if (table.Rows.Count > 0) { 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(); }
|
方法2:使用 JavaScriptSerializer
首先我们添加System.Web.Script.Serialization命名空间,如下:
1
| using System.Web.Script.Serialization;
|
JavaScriptSerializer这个类是由异步通信层内部使用来序列化和反序列化数据。如果序列化一个对象,就使用序列化方法。反序列化Json字符串,使用Deserialize或DeserializeObject方法。在这里,我们使用序列化方法得到Json格式的数据。代码以下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public string DataTableToJsonWithJavaScriptSerializer(DataTable table) { JavaScriptSerializer jsSerializer = new JavaScriptSerializer(); List < Dictionary < string, object >> parentRow = new List < Dictionary < string, object >> (); Dictionary < string, object > childRow; foreach(DataRow row in table.Rows) { childRow = new Dictionary < string, object > (); foreach(DataColumn col in table.Columns) { childRow.Add(col.ColumnName, row[col]); } parentRow.Add(childRow); } return jsSerializer.Serialize(parentRow); }
|
方法3:使用Json.Net DLL (Newtonsoft)
这个方法中要添加Json.Net DLL引用,我们可以从Newtonsoft下载Json.Net DLL,再导入命名空间,代码如下:
1 2 3 4 5 6 7 8
| using Newtonsoft.Json; public string DataTableToJsonWithJsonNet(DataTable table) { string JsonString=string.Empty; JsonString = JsonConvert.SerializeObject(table); return JsonString; }
|