Converts a able to a generic List <T> or JSON or datatablejson.
When developing ASP. NET Web APIs or ASP. net mvc, the data we get from the database is often DataSet or able. To make front-end JQuery easy to use the data, we need to convert the data into a generic List <T> or JSON.
Insus. NET has written this conversion function as an extension method:
Method source code:
Public static List <T> ToList <T> (this DataTable dt) {var columnNames = dt. columns. cast <DataColumn> (). select (c => c. columnName ). toList (); var properties = typeof (T ). getProperties (); return dt. asEnumerable (). select (row => {var objT = Activator. createInstance <T> (); foreach (var pro in properties) {if (columnNames. contains (pro. name) pro. setValue (objT, row [pro. name] = DBNull. value? String. Empty: row [pro. Name]. ToString (), null) ;}return objT ;}). ToList ();}View Code
Convert a able to JSON:
Method source code:
Public static string ToJson (this DataTable table) {List <Dictionary <string, object> list = new List <Dictionary <string, object> (); foreach (DataRow row in table. rows) {Dictionary <string, object> dict = new Dictionary <string, object> (); foreach (DataColumn col in table. columns) {dict [col. columnName] = row [col];} list. add (dict);} return serializer. serialize (list );}View Code
Instance application, you can refer to from the following: create and use Web API http://www.cnblogs.com/insus/p/5019088.html