Created
February 11, 2017 01:12
-
-
Save jburditt/0fd705cdfb64a1894c83fda146b907a0 to your computer and use it in GitHub Desktop.
DataReaderHelper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class DataTableHelpers | |
{ | |
public static IEnumerable<T> To<T>(this DataTable data) | |
{ | |
Mapper.Initialize(cfg => | |
{ | |
MapperRegistry.Mappers.Add(new AutoMapper.Data.DataReaderMapper { YieldReturnEnabled = true }); | |
}); | |
Mapper.CreateMap<IDataReader, T>(); | |
return Mapper.Map<IDataReader, IEnumerable<T>>(data.CreateDataReader()); | |
} | |
public static DataTable ToDataTable<T>(this IList<T> data) | |
{ | |
var props = TypeDescriptor.GetProperties(typeof(T)); | |
var table = new DataTable("DataTable"); | |
for (var i = 0; i < props.Count; i++) | |
{ | |
var prop = props[i]; | |
table.Columns.Add(prop.Name, prop.PropertyType); | |
} | |
var values = new object[props.Count]; | |
foreach (var item in data) | |
{ | |
for (var i = 0; i < values.Length; i++) | |
{ | |
values[i] = props[i].GetValue(item); | |
} | |
table.Rows.Add(values); | |
} | |
return table; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment