Almost everyone in the software knows that DataTable to object class conversion is often used. Commonly used is to assign values to objects using column names or indexed columns. If the number of columns is small, the number of columns is large, it's really annoying and prone to errors. it is also often plagued. this method has long been written. I have never had time. I was busy a few days ago. I have adapted some other methods by referring to some materials. I will share the following:
1. DataTable to List <T> Conversion
Public static List <T> DataTableToT <T> (DataTable source) where T: class, new ()
{
List <T> itemlist = null;
If (source = null | source. Rows. Count = 0)
{
Return itemlist;
}
Itemlist = new List <T> ();
T item = null;
Type targettype = typeof (T );
Type ptype = null;
Object value = null;
Foreach (DataRow dr in source. Rows)
{
Item = new T ();
Foreach (PropertyInfo pi in targettype. GetProperties ())
{
If (pi. CanWrite & source. Columns. Contains (pi. Name ))
{
Ptype = Type. GetType (pi. PropertyType. FullName );
Value = Convert. ChangeType (dr [pi. Name], ptype );
Pi. SetValue (item, value, null );
}
}
Itemlist. Add (item );
}
Return itemlist;
}
2. Conversion from DataRow to T
Public static T DataRowToT <T> (DataRow source) where T: class, new ()
{
T item = null;
If (source = null)
{
Return item;
}
Item = new T ();
Type targettype = typeof (T );
Type ptype = null;
Object value = null;
Foreach (PropertyInfo pi in targettype. GetProperties ())
{
If (pi. CanWrite & source. Table. Columns. Contains (pi. Name ))
{
Ptype = Type. GetType (pi. PropertyType. FullName );
Value = Convert. ChangeType (source [pi. Name], ptype );
Pi. SetValue (item, value, null );
}
}
Return item;
}
Note: 1. Reflection and generics are used in it, and they are both the most basic level.