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

{

    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 incollection Select x).ToDataTable();

 

 

Author : Naresh Joshi (MSFT) , SQL Developer Technical Lead, Microsoft