tipar datatable in dto c# code example
Example: tipar datatable in dto c#
Criando a classe para converter o DataTable para List
A seguir crie a classe Conversor com o método estático ConverterParaLista():
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace WF_DataTable_Objetos
{
public static class Conversor
{
public static List<T> ConverterParaLista<T>(DataTable dt)
{
var columnNames = dt.Columns.Cast<DataColumn>().Select(c => c.ColumnName.ToLower()).ToList();
var properties = typeof(T).GetProperties();
return dt.AsEnumerable().Select(row => {
var objT = Activator.CreateInstance<T>();
foreach (var pro in properties)
{
if (columnNames.Contains(pro.Name.ToLower()))
{
try
{
pro.SetValue(objT, row[pro.Name]);
}
catch (Exception)
{ }
}
}
return objT;
}).ToList();
}
}
}