Converting Collection to Dataset

Introduction
 
I saw there is always a need to convert a list to a dataset and then bind it to a datagrid. To make it reusable I used the C# extension method feature.
 
Solution
 
We first check to make sure a list is provided or we throw an ArgumentNullException (in the overloaded constructor we also check for the name parameter). Here’s how the two constructors look:
  1. public static DataSet ConvertToDataSet<T>(this IEnumerable<T> source, string name)  
  2. {  
  3.      if (source == null)  
  4.      throw new ArgumentNullException("source ");  
  5.      if (string.IsNullOrEmpty(name))  
  6.      throw new ArgumentNullException("name");  
  7.      var converted = new DataSet(name);  
  8.      converted.Tables.Add(NewTable(name, source));  
  9.      return converted;  

Where Name= Name of the DataTable to be added to the DataSet.
 
 Let’s have a look of the NewTable method:
  1. private static DataTable NewTable<T>(string name, IEnumerable<T> list)  
  2. {  
  3.      PropertyInfo[] propInfo = typeof(T).GetProperties();  
  4.      DataTable table = Table<T>(name, list, propInfo);  
  5.      IEnumerator<T> enumerator = list.GetEnumerator();  
  6.      while (enumerator.MoveNext())  
  7.      table.Rows.Add(CreateRow<T>(table.NewRow(), enumerator.Current, propInfo));  
  8.      return table;  

Here’s how CreateRow looks like: 
  1. private static DataRow CreateRow<T>(DataRow row, T listItem, PropertyInfo[] pi)  
  2. {  
  3.      foreach (PropertyInfo p in pi)  
  4.      row[p.Name.ToString()] = p.GetValue(listItem, null);  
  5.      return row;  

and the Table<T> method used in NewTable method: 
  1. private static DataTable Table<T>(string name, IEnumerable<T> list, PropertyInfo[] pi)  
  2. {  
  3.      DataTable table = new DataTable(name);  
  4.      foreach (PropertyInfo p in pi)  
  5.      table.Columns.Add(p.Name, p.PropertyType);  
  6.      return table;  

Use
 
So now lets take a look at using this to convert a Generic list into a DataSet. In this example we will create a simple Generic list which will contain only 2 items, we will then use the Extension we created to convert the list into a DataSet:
  1. var list = new List<Person>();  
  2. list.Add(new Person { ID = 1, Name = "Arunava" });  
  3. list.Add(new Person { ID = 2, Name = "Bubu" });  
  4. DataSet converted = list.ConvertToDataSet("TestTable"); 
Hope this helps.