How to convert an IEnumerable to a DataTable in the same way as we use ToList or ToArray

LINQ provides us some extension methods to convert an IEnumerable to a collection e.g. ToList(), ToArray() etc. But what if you want to convert the enumerable to a DataTable. There is no built in extension method for that currently.

                var v = (from x in collection Select x).ToDataTable();

But if required we can create our own extension method as shown below.

public static class Extenders

{

LINQ provides us some extension methods to convert an IEnumerable to a collection e.g. ToList(), ToArray() etc. But what if you want to convert the enumerable to a DataTable. There is no built in extension method for that currently.

                var v = (from x in collection Select x).ToDataTable();

But if required we can create our own extension method as shown below.

public static class Extenders

{

    public static DataTable ToDataTable<T>(this IEnumerable<T> collection, string tableName)

    {

        DataTable tbl = ToDataTable(collection);

        tbl.TableName = tableName;

        return tbl;

    }

    public static DataTable ToDataTable<T>(this IEnumerable<T> collection)

    {

        DataTable dt = new DataTable();

        Type t = typeof(T);

        PropertyInfo[] pia = t.GetProperties();

        //Create the columns in the DataTable

        foreach (PropertyInfo pi in pia)

        {

            dt.Columns.Add(pi.Name, pi.PropertyType);

        }

        //Populate the table

        foreach (T item in collection)

        {

            DataRow dr = dt.NewRow();

            dr.BeginEdit();

            foreach (PropertyInfo pi in pia)

            {

                dr[pi.Name] = pi.GetValue(item, null);

            }

            dr.EndEdit();

            dt.Rows.Add(dr);

        }

        return dt;

    }

}

Basically above code will create a DataTable with columns corresponding to the properties in the IEnumerable object. Then it will populate it with the data from that collection.

For calling it just import this namespace in your class and use it as shown below

      var v = (from x in collection Select x).ToDataTable();

 

 

Written by: Naresh Joshi (MSFT)

Comments

  • Anonymous
    April 08, 2009
    PingBack from http://www.anith.com/?p=27377
  • Anonymous
    April 16, 2009
    SharePoint Logging to the Workflow History List in SharePoint workflows Inconvenient SPWeb.GetListItem
  • Anonymous
    April 16, 2009
    You are voted (great) - Trackback from Web Development Community
  • Anonymous
    April 19, 2009
    Using jqGrid with ASP.NET MVC: Finally, A Solution How to improve the performances of ASP.NET MVC web