33using System . ComponentModel ;
44using System . Data ;
55using System . Linq ;
6+ using System . Threading ;
7+ using System . Threading . Tasks ;
68
79namespace EntityFrameworkCore . SqlServer . SimpleBulks . Extensions ;
810
911public static class IListExtensions
1012{
11- public static DataTable ToDataTable < T > ( this IEnumerable < T > data , IEnumerable < string > propertyNames , bool addIndexNumberColumn = false )
13+ public static DataTable ToDataTable < T > ( this IEnumerable < T > data , IEnumerable < string > propertyNames , bool addIndexNumberColumn = false , CancellationToken cancellationToken = default )
1214 {
15+ cancellationToken . ThrowIfCancellationRequested ( ) ;
16+
1317 var properties = TypeDescriptor . GetProperties ( typeof ( T ) ) ;
1418
1519 var updatablePros = new List < PropertyDescriptor > ( ) ;
1620 foreach ( PropertyDescriptor prop in properties )
1721 {
22+ cancellationToken . ThrowIfCancellationRequested ( ) ;
23+
1824 if ( propertyNames . Contains ( prop . Name ) )
1925 {
2026 updatablePros . Add ( prop ) ;
@@ -24,6 +30,8 @@ public static DataTable ToDataTable<T>(this IEnumerable<T> data, IEnumerable<str
2430 var table = new DataTable ( ) { MinimumCapacity = data . Count ( ) } ;
2531 foreach ( PropertyDescriptor prop in updatablePros )
2632 {
33+ cancellationToken . ThrowIfCancellationRequested ( ) ;
34+
2735 table . Columns . Add ( prop . Name , Nullable . GetUnderlyingType ( prop . PropertyType ) ?? prop . PropertyType ) ;
2836 }
2937
@@ -36,9 +44,13 @@ public static DataTable ToDataTable<T>(this IEnumerable<T> data, IEnumerable<str
3644
3745 foreach ( T item in data )
3846 {
47+ cancellationToken . ThrowIfCancellationRequested ( ) ;
48+
3949 var row = table . NewRow ( ) ;
4050 foreach ( PropertyDescriptor prop in updatablePros )
4151 {
52+ cancellationToken . ThrowIfCancellationRequested ( ) ;
53+
4254 var value = prop . GetValue ( item ) ?? DBNull . Value ;
4355 row [ prop . Name ] = value ;
4456 }
@@ -54,4 +66,12 @@ public static DataTable ToDataTable<T>(this IEnumerable<T> data, IEnumerable<str
5466 }
5567 return table ;
5668 }
69+
70+ public static async Task < DataTable > ToDataTableAsync < T > ( this IEnumerable < T > data , IEnumerable < string > propertyNames , bool addIndexNumberColumn = false , CancellationToken cancellationToken = default )
71+ {
72+ return await Task . Run ( ( ) =>
73+ {
74+ return data . ToDataTable ( propertyNames , addIndexNumberColumn , cancellationToken ) ;
75+ } , cancellationToken ) ;
76+ }
5777}
0 commit comments