Generic collection converted to DataTable

Source: Internet
Author: User

In the project, encountered the use of converting a collection to a DataTable, read the information on the Internet, recorded here, and shared.

usingSystem;usingSystem.Collections.Generic;usingSystem.Data;usingSystem.Linq;usingSystem.Reflection;usingSystem.Text;usingSystem.Threading.Tasks;namespacewolfy.list2datatable{classProgram {Static voidMain (string[] args) {List<Person> LST =NewList<person>()             {                 NewPerson () {id=1, gender=false, name="wolfy1"},                 NewPerson () {id=2, gender=false, name="wolfy2"},                  NewPerson () {id=3, gender=false, name="Wolfy3"},                   NewPerson () {id=4, gender=false, name="Wolfy4"},                    NewPerson () {id=5, gender=false, name="wolfy5"},            }; DataTable DT= list2datatable<person>(LST); Console.WriteLine ("End of conversion");        Console.read (); }        /// <summary>        ///convert a generic collection to a DataTable/// </summary>        /// <typeparam name= "TEntity" ></typeparam>        /// <param name= "entities" ></param>        /// <returns></returns>        StaticDataTable list2datatable<tentity> (list<tentity>entities) {            if(Entities = =NULL)            {                Throw NewArgumentNullException ("The collection of conversions is empty"); } Type Type=typeof(TEntity); Propertyinfo[] Properties=type.            GetProperties (); DataTable DT=NewDataTable (type.            Name); foreach(varIteminchproperties) {dt. Columns.Add (NewDataColumn (item. Name) {DataType =item.            PropertyType}); }            foreach(varIteminchentities) {DataRow row=dt.                NewRow (); foreach(varPropertyinchproperties) {Row[property. Name]=Property .                GetValue (item); } dt.            Rows.Add (row); }            returnDT; }    }     Public classPerson { Public intID {Set;Get; }  Public stringName {Set;Get; }  Public BOOLGender {Set;Get; } }}

Generic collection converted to DataTable

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.