Есть ли хороший способ конвертировать IEnumerable в DataTable?
Я мог бы использовать отражение, чтобы получить свойства и значения, но это кажется немного неэффективным, есть ли что-то встроенное?
(Я знаю примеры вроде: ObtainDataTableFromIEnumerable)
ИЗМЕНИТЬ:
Этот question уведомил меня о проблеме обработки нулевых значений.
Код, который я написал ниже, правильно обрабатывает нулевые значения.
public static DataTable ToDataTable<T>(this IEnumerable<T> items) {
// Create the result table, and gather all properties of a T
DataTable table = new DataTable(typeof(T).Name);
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
// Add the properties as columns to the datatable
foreach (var prop in props) {
Type propType = prop.PropertyType;
// Is it a nullable type? Get the underlying type
if (propType.IsGenericType && propType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
propType = new NullableConverter(propType).UnderlyingType;
table.Columns.Add(prop.Name, propType);
}
// Add the property values per T as rows to the datatable
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);
table.Rows.Add(values);
}
return table;
}