Convert a generic List to DataTable

/// <summary>
/// Converts an IList to a DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data"></param>
/// <returns></returns>
public static DataTable ToDataTable<T>(this IList<T> data) {
	PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
	DataTable table = new DataTable();
	for (int i = 0; i < props.Count; i++) {
		PropertyDescriptor prop = props[i];
		table.Columns.Add(
			prop.Name,
			prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ?
				prop.PropertyType.GetGenericArguments()[0]
				:
				prop.PropertyType
		);
	}
	object[] values = new object[props.Count];
	foreach (T item in data) {
		for (int i = 0; i < values.Length; i++) {
			values[i] = props[i].GetValue(item);
		}
		table.Rows.Add(values);
	}
	return table;
}

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>