Conversion between DataTable and List

List to DataTable:

public static DataTable ToDataTable<T>(IEnumerable<T> collection)
        {
            var props = typeof(T).GetProperties();
            var dt = new DataTable();
            dt.Columns.AddRange(props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray());
            if (collection.Count() > 0)
            {
                for (int i = 0; i < collection.Count(); i++)
                {
                    ArrayList tempList = new ArrayList();
                    foreach (PropertyInfo pi in props)
                    {
                        object obj = pi.GetValue(collection.ElementAt(i), null);
                        tempList.Add(obj);
                    }
                    object[] array = tempList.ToArray();
                    dt.LoadDataRow(array, true);
                }
            }
            return dt;
        }
    }

DataTable to List:

public class ModelConvertHelper<T> where T : new()
    {
        public static List<T> ConvertToModel(DataTable dt)
        {
            // Define the collection     
            List<T> ts = new List<T> ();

            // Get the type of this model    
            Type type = typeof (T);
             string tempName = "" ;

            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                 // Get the public properties of this model       
                PropertyInfo[] properties = t.GetType().GetProperties();
                 foreach (PropertyInfo pi in properties)
                {
                    tempName = pi.Name;   // Check if DataTable contains this column    

                    if (dt.Columns.Contains(tempName))
                    {
                        // Determine whether this property has a Setter       
                        if (!pi.CanWrite) continue ;

                        object value = dr[tempName];
                        if (value != DBNull.Value)
                            pi.SetValue(t, value, null);
                    }
                }
                ts.Add(t);
            }
            return ts;
        }
    }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324939649&siteId=291194637