Skip to content

Instantly share code, notes, and snippets.

@chris84948
Created August 11, 2016 13:50
Show Gist options
  • Save chris84948/feaf487264eeb560ebd1b928799d765f to your computer and use it in GitHub Desktop.
Save chris84948/feaf487264eeb560ebd1b928799d765f to your computer and use it in GitHub Desktop.
using FastMember;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
namespace SQLSpeedTester
{
public static class Helper
{
private static readonly IDictionary<Type, IEnumerable<PropertyInfo>> _Properties =
new Dictionary<Type, IEnumerable<PropertyInfo>>();
/// <summary>
/// Converts a DataTable to a list with generic objects
/// </summary>
/// <typeparam name="T">Generic object</typeparam>
/// <param name="table">DataTable</param>
/// <returns>List with generic objects</returns>
public static IEnumerable<T> DataTableToList<T>(this DataTable table) where T : class, new()
{
try
{
var objType = typeof(T);
IEnumerable<PropertyInfo> properties;
lock (_Properties)
{
if (!_Properties.TryGetValue(objType, out properties))
{
properties = objType.GetProperties().Where(property => property.CanWrite);
_Properties.Add(objType, properties);
}
}
var list = new List<T>(table.Rows.Count);
foreach (var row in table.AsEnumerable().Skip(1))
{
var obj = new T();
foreach (var prop in properties)
{
try
{
Type t = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
object propertyValue = (row[prop.Name] == null) ? null : Convert.ChangeType(row[prop.Name], t);
var accessors = TypeAccessor.Create(objType);
accessors[obj, prop.Name] = propertyValue;
}
catch
{
}
}
list.Add(obj);
}
return list;
}
catch
{
return Enumerable.Empty<T>();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment