Convert LiNQ resultset to DataTable

When the LiNQ to SQL framework was originally released in BETA there was a built in extension method to convert the LiNQ result to either a DataTable or DataSet if I remember correctly. However when it came to release this disappeared for some strange reason.

Now I’m sure MS had their reasons for removing it but I don’t care and want it back ;) So I’ve written a little extension method to convert the LiNQ resultset to a DataTable using a bit of Reflection. Here’s the code and enjoy! As always, I take no responsibility for its usage ;)

/// <summary>
/// Converts an IEnumerable type collection into a DataTable
/// </summary>
/// <param name=”collection”>Collection type that implements IEnumberable</param>
/// <returns>Datatable representing IEnumerable collection</returns>
public static DataTable ToDataTable<T>(this IEnumerable<T>collection)
{
// Create DataTable to Fill
DataTable _newDataTable = new DataTable();

// Retrieve the Type passed into the Method
Type _impliedType = typeof(T);

//Get an array of the Type’s properties
PropertyInfo[] _propInfo = _impliedType.GetProperties();

//Create the columns in the DataTable
foreach (PropertyInfo pi in _propInfo)
{
_newDataTable.Columns.Add(pi.Name, pi.PropertyType);
}

//Populate the table
foreach (T item in collection)
{
DataRow _newDataRow = _newDataTable.NewRow();
_newDataRow.BeginEdit();

foreach (PropertyInfo pi in _propInfo)
{
_newDataRow[pi.Name] = pi.GetValue(item, null);
}

_newDataRow.EndEdit();
_newDataTable.Rows.Add(_newDataRow);
}

return _newDataTable;
}

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*