Converting a List to a DataTable






4.98/5 (26 votes)
I wrote this because I was interested in a Q&A question which asked for exactly that. Since I quite often use DataTables to transfer data, and to display it for debugging I knocked up an extension method to do it.
Then I realized that arrays implement the
IList
interface... Hmm. So now, I have an Extension Method that converts any List
or array based data into a DataTable
.
For debugging, that's pretty useful...
So, here it is, for posterity:
public static class ExtensionMethods
{
/// <summary>
/// Converts a List to a datatable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <returns></returns>
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable dt = new DataTable();
for (int i = 0; i < properties.Count; i++)
{
PropertyDescriptor property = properties[i];
dt.Columns.Add(property.Name, property.PropertyType);
}
object[] values = new object[properties.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = properties[i].GetValue(item);
}
dt.Rows.Add(values);
}
return dt;
}
}
Public NotInheritable Class ExtensionMethods
''' <summary>
''' Converts a List to a datatable
''' </summary>
''' <typeparam name="T"></typeparam>
''' <param name="data"></param>
''' <returns></returns>
<System.Runtime.CompilerServices.Extension> _
Public Shared Function ToDataTable(Of T)(data As IList(Of T)) As DataTable
Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(GetType(T))
Dim dt As New DataTable()
For i As Integer = 0 To properties.Count - 1
Dim [property] As PropertyDescriptor = properties(i)
dt.Columns.Add([property].Name, [property].PropertyType)
Next
Dim values As Object() = New Object(properties.Count - 1) {}
For Each item As T In data
For i As Integer = 0 To values.Length - 1
values(i) = properties(i).GetValue(item)
Next
dt.Rows.Add(values)
Next
Return dt
End Function
End Class