C# How To Convert DataTable To List Of Entities

Do you like this?

This snippet helps you convert a datatable to a list of entities.


using System.Data;
using System.Reflection;

public static List convert(DataTable table) {
	List res = new List();
	if (table == null) return res;

	Type classType = typeof(T);
	PropertyInfo[] propertyInfos= classType.GetProperties();

	if (propertyInfos.Count() == 0) return res; // there is no property to set value

	List columns= table.Columns.Cast().ToList();
	foreach (DataRow row in table.Rows){
		T t = Activator.CreateInstance();
		foreach (PropertyInfo propertyInfo in propertyInfos) {
			DataColumn column = columns.Find(col => col.ColumnName == propertyInfo.Name);
			if (column != null)
				propertyInfo.SetValue(t, row[column]);
	return res;

comments powered by Disqus