Created
April 27, 2017 15:00
-
-
Save feload/49592ffdeb6eb120084098781d5c6665 to your computer and use it in GitHub Desktop.
Convert DataTable to a generic list - extension method
This file contains hidden or 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
using System; | |
using System.Collections.Generic; | |
using System.Data; | |
using System.Linq; | |
using System.Reflection; | |
using System.Web; | |
namespace helper | |
{ | |
/// <summary> | |
/// Static helper class for utility functions | |
/// </summary> | |
public static class Helper | |
{ | |
/// <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 List<T> DataTableToList<T>(this DataTable table) where T : class, new() | |
{ | |
try | |
{ | |
List<T> list = new List<T>(); | |
foreach (var row in table.AsEnumerable()) | |
{ | |
T obj = new T(); | |
foreach (var prop in obj.GetType().GetProperties()) | |
{ | |
try | |
{ | |
PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name); | |
propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null); | |
} | |
catch | |
{ | |
continue; | |
} | |
} | |
list.Add(obj); | |
} | |
return list; | |
} | |
catch | |
{ | |
return null; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment