19 December 2013

Convert List<object> to the DataTable in C#

Hi Friends,

Lets see how to convert the List to the DataTable. Sometime we encounter such a situation that we require to convert the List of the object to the DataTable.

See the below diagram can tell you the correct requirement.

class MyLocation
{        
    private string _name;
    private string _desc;
    private string _path;
        
    public string Name { get { return _name; } set { _name = value; } }
    public string Description { get { return _desc; } set { _desc = value; } }
    public string Path { get { return _path; } set { _path = value; } }

    public MyLocation(string Name, string Description, string Path)
    {
        this.Name = Name;
        this.Description = Description;
        this.Path = Path;
    }
}

We have the list of the object as follow
    ..
    ..
    // create the list for the "MyLocation" Objects
    List<MyLocation> list = new List<MyLocation>();

    // add the "MyLocation" Objects to the list
    list.Add(new MyLocation("name1", "desc1", "path1"));  
    list.Add(new MyLocation("name2", "desc2", "path2"));
    list.Add(new MyLocation("name3", "desc3", "path3"));
    ..
    ..

Now I want to convert this list to the DataTable as
NameDescriptionPath
name1desc1path1
name2desc2path2
name3desc3path3
You have to implement the code which will get the object one by one from the list and get all the properties of the object and create the DataTable according to that.  And then add all the properties of the object as a DataRow in DataTable and then return that DataTable.

I have done this part for you, you just need to copy-paste the following code and use it.
public DataTable ConvertToDataTable<T>(List<T> data)
{
    // get the properties of the Object inside the List
    PropertyDescriptorCollection properties =
       TypeDescriptor.GetProperties(typeof(T));

    // create the DataTable
    DataTable table = new DataTable();

    // read the properties one-by-one and add the Name as 
    // column in the DataTable table
    foreach (PropertyDescriptor prop in properties)
    {
      table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
    }

    // now read the Object in the list one-by-one and
    // add the properties of object in DataRow,
    //and finally add DataRow row in DataTable table
    foreach (T item in data)
    {
      DataRow row = table.NewRow();
      foreach (PropertyDescriptor prop in properties)
      {
        row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
      }
      table.Rows.Add(row);
    }

    // finally return the DataTable
    return table;

}
Thats it..!!!
Happy Code Sharing.. :)

No comments:

Post a Comment