public static DataTable ToDataTable<TSource>(this IEnumerable<TSource> source )
{
if ( source == null )
return null;
DataTable table = new DataTable ( );
PropertyInfo [] oProps = null;
foreach ( TSource item in source )
{
if ( oProps == null )
{
oProps = ( ( Type ) item . GetType ( ) ) . GetProperties ( );
foreach ( PropertyInfo pro in oProps )
{
Type colType = pro . PropertyType;
if ( ( colType . IsGenericType ) && ( colType . GetGenericTypeDefinition ( ) == typeof ( Nullable<> ) ) )
{
colType = colType . GetGenericArguments ( ) [ 0 ];
}
table . Columns . Add ( new DataColumn ( pro . Name , colType ) );
}
}
DataRow row = table . NewRow ( );
foreach ( PropertyInfo info in oProps )
{
row [ info . Name ] = info . GetValue ( item , null ) ?? DBNull . Value;
}
table . Rows . Add ( row );
}
return table;
}
//调用方法
var query = table.AsEnumerable().Select ( ( x ) => new{
x1=x . Field<int> ( "x1" ),
x2=x . Field<int> ( "x2" )
}). ToDataTable ( );