Friday, February 19, 2016

Convert List to Dataset

       public DataSet ToDataSet<T>(IList<T> list)
       {
           Type elementType = typeof(T);
           using (DataSet ds = new DataSet())
           {
               using (DataTable t = new DataTable())
               {
                   ds.Tables.Add(t);
                   //add a column to table for each public property on T
                   PropertyInfo[] _props = elementType.GetProperties();
                   foreach (PropertyInfo propInfo in _props)
                   {
                       Type _pi = propInfo.PropertyType;
                       Type ColType = Nullable.GetUnderlyingType(_pi) ?? _pi;
                       t.Columns.Add(propInfo.Name, ColType);
                   }
                   //go through each property on T and add each value to the table
                   foreach (T item in list)
                   {
                       DataRow row = t.NewRow();
                       foreach (PropertyInfo propInfo in _props)
                       {
                           row[propInfo.Name] = propInfo.GetValue(item, null) ??                                       DBNull.Value;
                       }
                       t.Rows.Add(row);
                   }
               }
               return ds;

           }