Wednesday, April 24, 2013

How To- Convert a Generic List to a Datatable

Today when I was working I my project, I need to convert the List into a DataTable for some reasons. I goggled it and get some solutions for this. But I get a very good solution Here.So I am posting that solution for my readers.

In my previous posts, I explained Get Property Names using Reflection in C#Hard drive information using C#Create Directory/Folder using C#Check Internet Connection using C#SQL Server Database BackUp using C#Partial Methods, Contextual KeywordC# Static Methods and some other articles related to C#ASP.Net and SQL Server.

Here,I have not constrained reference type or value type only. We need to take care of both the cases while converting List to DataTable as the underlying type can be both value or reference type.


So,for converting List to DataTable write the following method as shown below.Before use the function shown below don't forget to add the following namespaces-
using System.Collections.Generic;
using System.Data;
using System.Reflection; 

After adding above namspaces write the following function for converting List to DataTable.

public static DataTable ListToDataTable<T>(IList<T> varlist)
{
  DataTable dt = new DataTable();

  //special handling for value types and string
  //In value type, the DataTable is expected to contain the values of all the variables (items) present in List.
  //Hence I create only one column in the DataTable named “Values”,
  //Though String is a reference type, due to its behavior 
  //I treat it as a special case and handle it as value type only.
  if (typeof(T).IsValueType || typeof(T).Equals(typeof(string)))
  {
    DataColumn dc = new DataColumn("Values");

    dt.Columns.Add(dc);

    foreach (T item in varlist)
    {
      DataRow dr = dt.NewRow();
      dr[0] = item;
      dt.Rows.Add(dr);
      }
   }
   //for reference types other than  string
   // Used PropertyInfo class of System.Reflection
   else
   {

     //find all the public properties of this Type using reflection
     PropertyInfo[] propT = typeof(T).GetProperties();

     foreach (PropertyInfo pi in propT)
     {
     //create a datacolumn for each property
     DataColumn dc = new DataColumn(pi.Name, pi.PropertyType);
     dt.Columns.Add(dc);
     }

     //now we iterate through all the items , take the corresponding values and add a new row in dt
     for (int item = 0; item < varlist.Count(); item++)
     {
        DataRow dr = dt.NewRow();

        for (int property = 0; property < propT.Length; property++)
        {
           dr[property] = propT[property].GetValue(varlist[item], null);
        }

        dt.Rows.Add(dr);
     }
   }
   dt.AcceptChanges();
   return dt;
}
I hope this will be helpful for you. I would like to have any feedback from you. Your valuable feedback, question, or comments about this article are always welcome.

No comments:

Post a Comment

If You Enjoyed This Post Please Take 5 Seconds To Share It.

^ Scroll to Top hgpromo