How C # DataTable and list convert to each other

Source: Internet
Author: User

First, the non-generic conversions are done by traversing the DataTable and assigning values to the same fields in the model.

Using the ToList method of LINQ, Non-generic
        Static list<entity> ConvertTo (DataTable DT)
        {
            Null
            Null
            New List<entity> ();
            In dt. Rows
                    New Entity
                    {
                        PID = Int32.Parse (dr["pid"). ToString ()),
                        PName = dr["PName"]. ToString (),
                        Ppass = dr["Ppass"]. ToString (),
                        PADDR = dr["Paddr"]. ToString ()
                    }). ToList ();
            return list;
        }

The code is simple, it's just a loop assignment. Here I use the model test class as follows:

Namespace Datasettoentity.code
{
    Class Entity
    {
        int PID {get; set;}
        String PName {get; set;}
        String Ppass {get; set;}
        String Paddr {get; set;}
    }
}

Generic mode

Then, since the non-generic version is not universal, here we are going to implement it with the generic version, because the generic version is the attribute structure in the unpredictable model, so here we need to introduce reflection to do it.

A generic method that uses reflection
        New ()
        {
            Null
            Null
            New List<t> ();
            Try
            {
                list<New list<string> ();   
                In dt. Columns)
                {
                    Columnsname.add (Datacolumn.columnname); //Get all the table headers
                }
                list = dt. AsEnumerable (). ToList (). convertall<t> (row = getobject<t> (row, columnsname));  //Conversion
                return list;
            }
            catch (Exception ex)
            {
                Null
            }
        }
        Static T getobject<t> (DataRow row, list<new ()
        {
            New T ();
            Try
            {
                "";
                "";
                typeof (T). GetProperties ();
                In properties)  //Traverse property of T
                {
                    Look for header names that can be matched
                    if (!  String. IsNullOrEmpty (columnname))
                    {
                        Value = Row[columnname]. ToString ();
                        if (!  String. IsNullOrEmpty (value)) 
                        {
                            A matching table header exists
                            {
                                Value = Row[columnname]. ToString (). Replace (""). Replace (//extract data from a DataRow 
                                Objproperty.setvalue (obj, Convert.changetype (//assignment Operation
                            }
                            Else
                            {
                                Value = Row[columnname]. ToString (). Replace (//There is a matching table header
                                Objproperty.setvalue (obj, convert.changetype (null);  Assignment Operation 
                            }
                        }
                    }
                }
                return obj;
            }
            Catch
            {
                return obj;
            }
        }
The above is mainly through reflection gets the property name of T, and then matches the header in the DataRow, if it matches, it is assigned value. Here is its simplified version:
Using the reflection of the generic method two
        New ()
        {
            Null
            Null
            New List<t> ();
            typeof (T);
            propertyinfo[] Propertyinfos = type. GetProperties ();  //Gets the properties of the generic type
            list<datacolumn> listcolumns = dt. Columns.cast<datacolumn> (). ToList ();  //Gets the header of the dataset for easy matching
            T T;
            In dt. Rows)   
            {
                New T ();
                In Propertyinfos)
                {
                    Try
                    {
                        DataColumn dcolumn = listcolumns.find (name = = name. ToString (). ToUpper () = = PropertyInfo.Name.ToUpper ());  //See if there is a corresponding column name
                        Null
                            NULL);  //Assigned value
                    }
                    catch (Exception ex)
                    {
                        New Exception (ex. Message);
                    }
                }
                List. ADD (t);
            }
            return list;
        }
As for how to use it, it is very simple to use the following code directly:
list<entity> list = commonutils.converttoex<entity> (dt);

References are only for learning purposes.

How C # DataTable and list convert to each other

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.