Dhi*_*ina 5 linq asp.net datatable
我需要将LINQ转换为DataTable.
我从StackOverflow中窃取了以下扩展方法:
public static DataTable ToDataTable<T>(this IEnumerable<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;
}
Run Code Online (Sandbox Code Playgroud)
当表包含空值时,它会抛出异常.(即)
DataSet does not support System.Nullable<>
Run Code Online (Sandbox Code Playgroud)
委托(十进制类型)列包含空值)
在
tb.Columns.Add(prop.Name, prop.PropertyType);
Run Code Online (Sandbox Code Playgroud)
怎么解决?
这是一个拉皮条版本:
public static DataTable ToDataTable<T>(this IEnumerable<T> items) {
DataTable table = new DataTable(typeof(T).Name);
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
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);
}
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;
}
Run Code Online (Sandbox Code Playgroud)
编辑:修改我的代码,测试它,它的工作原理!:)