我有一个扩展方法,可以将
IEnumerable<T>
转换为数据表。它当前处理 T
类型的所有公共实例属性,并将它们作为列添加到 DataTable
`public static DataTable ToDataTable<T>(this IEnumerable<T> items)
{
var dataTable = new DataTable("Table");
var itemType = typeof(T);
var props = itemType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
var dateTimeProperties = props.Where(p => p.PropertyType == typeof(DateTime)).ToList();
// Add all properties as columns
foreach (var prop in props)
{
dataTable.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
// Populate the rows
foreach (var item in items)
{
var values = props.Select(prop =>
{
var value = prop.GetValue(item, null);
// Handle DateTime formatting
if (dateTimeProperties.Contains(prop))
{
value = ((DateTime)value!).ToString("dd-MMM-yyyy");
}
return value;
}).ToArray();
dataTable.Rows.Add(values);
}
return dataTable;
}`
我想扩展此方法以允许根据用户的输入选择性地包含或排除列。我想介绍两个参数。
columnNames:用于过滤的可选列名称列表。 includeColumns:一个布尔值,指示是包含(true)还是排除(false)columnNames 中的列。
public static DataTable ToDataTable<T>(this IEnumerable<T> items, string[] columnNames, bool includ = true)
var filteredProps = includeColumns ? props.Where(p => columnNames == null || columnNames.Contains(p.Name)) : props.Where(p => columnNames == null || !columnNames.Contains(p.Name));
var propertyInfos = filteredProps.ToList();
//In Variable `propertyInfos` u will have now all the Filtered Properties.
foreach (var prop in propertyInfos)
{
dataTable.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}