You can create your own CopyToDataTable , which accepts any type of IEnumerable (not just DataRow ) and returns a new DataTable :
// following would not compile by default // because input is not an IEnumerable<DataRow> but an anonymous type var tblResult = bmwCars.CopyToDataTable();
Here is the implementation (using MSDN ):
public class ObjectShredder<T> { private System.Reflection.FieldInfo[] _fi; private System.Reflection.PropertyInfo[] _pi; private System.Collections.Generic.Dictionary<string, int> _ordinalMap; private System.Type _type;
Now you can add these extensions:
public static class CustomLINQtoDataSetMethods { public static DataTable CopyToDataTable<T>(this IEnumerable<T> source) { return new ObjectShredder<T>().Shred(source, null, null); } public static DataTable CopyToDataTable<T>(this IEnumerable<T> source, DataTable table, LoadOption? options) { return new ObjectShredder<T>().Shred(source, table, options); } }
Voila! Now CopyToDataTable works with any type of IEnumerable<T> :)
Tim schmelter
source share