Transform a C# list into a DataTable

Transform a C# list into a DataTable

Just a quick post about a very handy method I found on Stack Overflow. This lets you transform a list of C# objects into a data table. This can be very handy for debugging purposes, if nothing else. Being able to quickly see a large list of objects and all of their properties in one nice condensed view. Credit to Harshil Raval at http://stackoverflow.com/questions/18100783/how-to-convert-a-list-into-data-table


private DataTable ToDataTable<T>(List<T> items)
{
	var tb = new DataTable(typeof(T).Name);

	PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

	foreach (var prop in props)
	{
		tb.Columns.Add(prop.Name, prop.PropertyType);
	}

	foreach (var item in items)
	{
		var values = new object[props.Length];
		for (var i = 0; i < props.Length; i++)
		{
			values[i] = props[i].GetValue(item, null);
		}

		tb.Rows.Add(values);
	}

	return tb;
}

By | 2016-01-29T08:59:53+00:00 January 29th, 2016|Categories: C#|0 Comments

About the Author:

Leave A Comment