Converts a able to a generic List & lt; T & gt; or JSON or datatablejson.

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.