Created
April 18, 2019 15:38
-
-
Save Programazing/9d4cd4a2af6b0eec5cece80228d59b1e to your computer and use it in GitHub Desktop.
An extension method to convert a List of any type to a DataTable.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static DataTable ToDataTable<T>(this List<T> input) | |
{ | |
var props = TypeDescriptor.GetProperties(typeof(T)); | |
var output = new DataTable(); | |
foreach(PropertyDescriptor item in props) | |
{ | |
if (item.PropertyType.IsGenericType && item.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) | |
output.Columns.Add(item.Name, item.PropertyType.GetGenericArguments()[0]); | |
else | |
output.Columns.Add(item.Name, item.PropertyType); | |
} | |
var values = new object[props.Count]; | |
foreach (T item in input) | |
{ | |
for (int i = 0; i < values.Length; i++) | |
{ | |
values[i] = props[i].GetValue(item); | |
} | |
output.Rows.Add(values); | |
} | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment