Tuesday, April 30, 2013

How To- Convert Data Table into List

DataTable To List
Recently I have posted an article Convert a Generic List to a Datatable. Today I am explaining here the reverse way of my previous article i.e conversion of DataTable into List.

You may also like these posts 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.

 So Lets start the conversion of DataTable into List. First of all add the following namespaces-

using System.Collections.Generic;
using System.Data;
using System.Reflection;

Now write  the following function for DataTable into List-

/// <summary>
/// Converts DatATable into List
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <returns></returns>
public static IList<T> ConvertToList<T>(DataTable table)
{
   if (table == null)
   return null;
   List<DataRow> rows = new List<DataRow>();
   foreach (DataRow row in table.Rows)
   rows.Add(row);
   return ConvertTo<T>(rows);
}

In the above function we are calling an internal function name ConvertTo<T>(rows) which is shown below-

/// <summary>
/// Converts DataRows in T type list
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="rows"></param>
/// <returns></returns>
public static IList<T> ConvertTo<T>(IList<DataRow> rows)
{
   IList<T> list = null;
   if (rows != null)
   {
     list = new List<T>();
     foreach (DataRow row in rows)
     {
       T item = CreateItem<T>(row);
       list.Add(item);
     }
   }
    return list;
}
Above function takes list of DataRows as input.  In the function we are fetching all the DataRow through the iteration and passing each DataRow into function CreateItem<T>(row) which returns the item of List of type <T>. Here is the CreateItem<T>(row) function shown below-
/// <summary>
/// Convert DataRow into T Object
/// </summary>   
public static T CreateItem<T>(DataRow row)
{
  string columnName;      
  T obj = default(T);
  if (row != null)
  {
    //Create the instance of type T
    obj = Activator.CreateInstance<T>();           
    foreach (DataColumn column in row.Table.Columns)
    {
      columnName = column.ColumnName;
      //Get property with same columnName
      PropertyInfo prop = obj.GetType().GetProperty(columnName);                
      try
      {
          //Get value for the column
          object value = (row[columnName].GetType() == typeof(DBNull))? null : row[columnName];
          //Set property value
         prop.SetValue(obj, value, null);
      }
      catch
      {
         throw;
         //Catch whatever here
      }
   }
  }
  return  obj;
}

In the above function we creating the item of List of type T . In the function we are  create the instance of Type T using the CreateInstance<T>() method of Activator Class  and getting the property information of Type T and set the value of property using SetValue() method of  PropertyInfo Class.

So In short you can convert the DataTable into List by using above three methods.

 

Important Note for using above methods-

  • Your Type T  must have contain parameter less constructor for creating instance using CreateInstance<T>() method of Activator Class.
  • Type T must have the properties of the same name as column name of DataTable.

Note- I am not taken the credit of code above because I actually got this from here.

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

^ Scroll to Top