C#.net Development List and DataTable conversion

Source: Internet
Author: User

1. DataTable to List Collection
        /// <summary>        ///DataTable converted to list collection/// </summary>        /// <typeparam name= "T" >Entity Objects</typeparam>        /// <param name= "DT" >DataTable Table</param>        /// <param name= "Isstoredb" >Whether to save the database datetime field, the Date field is OK, check out not to Judge</param>        /// <returns>returns the list collection</returns>         Public StaticList<t> tabletolist<t> (DataTable DT,BOOLIsstoredb =true) {List<T> list =NewList<t>(); Type type=typeof(T); //list<string> listcolums = new list<string> ();propertyinfo[] Parray = type. GetProperties ();//array of collection properties             foreach(DataRow rowinchdt. Rows) {T entity= Activator.createinstance<t> ();//New Object Instance               foreach(PropertyInfo PinchParray) {                   if(!dt. Columns.contains (p.name) | | Row[p.name] = =NULL|| Row[p.name] = =dbnull.value) {Continue;//There is no collection attribute in the DataTable column or the field content is empty, jump out of the loop and proceed to the next loop                  }                                  if(isstoredb && P.propertytype = =typeof(DateTime) && convert.todatetime (Row[p.name]) < Convert.todatetime ("1753-01-01"))                     {                      Continue; }                   Try {                    varobj = Convert.changetype (Row[p.name], p.propertytype);//type strong turn, Convert table field type to collection field typeP.setvalue (Entity, obj,NULL); }                   Catch(Exception) {//throw;                   }                                       //if (Row[p.name]. GetType () = = P.propertytype)//{                   //P.setvalue (Entity, Row[p.name], null);//if the type exception is not considered, this is the only sentence below foreach.//}                                       //object obj = null; //if (Converttype (Row[p.name], p.propertytype,isstoredb, out obj))//{                                                           //P.setvalue (entity, obj, NULL); //}                } list.            ADD (entity); }           returnlist; }

The Isstoredb parameter is the Datatale data that considers the list conversion to not store the database, SQL Server data, the time type Date and datetime range, the date time range is January 1 to December 31, 9999 in the same period, The DateTime range is from January 1, 1753 to December 31, 9999, the time that is not in the range is stored to the database, resulting in an exception, and therefore time-qualified, by default to the data in the database.

2. List set to DataTable
        /// <summary>        ///List Collection go to DataTable/// </summary>        /// <typeparam name= "T" >entity Type</typeparam>        /// <param name= "List" >Incoming Collection</param>        /// <param name= "Isstoredb" >Whether to save the database datetime field, date time range Nothing, remove the display without setting true</param>        /// <returns>return DataTable Results</returns>         Public StaticDataTable listtotable<t> (list<t> List,BOOLIsstoredb =true) {Type TP=typeof(T); Propertyinfo[] Proinfos=TP.            GetProperties (); DataTable DT=NewDataTable (); foreach(varIteminchProinfos) {dt. Columns.Add (item. Name, item. PropertyType); //add list and corresponding type            }            foreach(varIteminchlist) {DataRow Dr=dt.                NewRow (); foreach(varProinfoinchProinfos) {                    Objectobj =Proinfo.getvalue (item); if(obj = =NULL)                    {                        Continue; }                    //if (obj! = null)// {                    if(isstoredb && Proinfo.propertytype = =typeof(DateTime) && convert.todatetime (obj) < Convert.todatetime ("1753-01-01"))                    {                        Continue; }                    //Dr[proinfo.name] = Proinfo.getvalue (item);Dr[proinfo.name] =obj; // }} dt.            Rows.Add (DR); }            returnDT; }

3. Extracting a row from a DataTable to a specified object
        /// <summary>        ///table specifies row to object/// </summary>        /// <typeparam name= "T" >Entity</typeparam>        /// <param name= "DT" >the incoming table</param>        /// <param name= "rowindex" >table row index, default to First row</param>        /// <returns>return entity Object</returns>         Public StaticT tabletoentity<t> (DataTable DT,introwindex =0,BOOLIsstoredb =true) {Type type=typeof(T); T Entity= Activator.createinstance<t> ();//creating an Object instance            if(dt = =NULL)            {                returnentity; }            //if (dt! = NULL)//{DataRow row = dt. Rows[rowindex];//the row index to querypropertyinfo[] Parray =type.            GetProperties (); foreach(PropertyInfo PinchParray) {                if(!dt. Columns.contains (p.name) | | Row[p.name] = =NULL|| Row[p.name] = =dbnull.value) {Continue; }                 if(isstoredb && P.propertytype = =typeof(DateTime) && convert.todatetime (Row[p.name]) < Convert.todatetime ("1753-01-02"))                {                    Continue; }                Try                {                    varobj = Convert.changetype (Row[p.name], p.propertytype);//type strong turn, Convert table field type to Object field typeP.setvalue (Entity, obj,NULL); }                Catch(Exception) {//throw;                }                //P.setvalue (Entity, Row[p.name], NULL);             }            //  }            returnentity; }

C#.net Development List and DataTable conversion

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.