Using the following method you can convert the DataTable into a List
For example you have the following DataTable:
DataTable resultTable = ConvertToDataTableFromList(realTimeSalesInput.RealTimeSales);
DataTable salesDt = new DataTable("RealTimeSales");
salesDt.Columns.Add("StoreNumber", typeof(string));
salesDt.Columns.Add("Value", typeof(decimal));
//Test Data
salesDt.Rows.Add(100, "A100", 100);
salesDt.Rows.Add(101, "B100", 101);
salesDt.Rows.Add(102, "C100", 102);
Now you can call the following function to provide the List from the given DataTable.
/// <summary>
/// RealTimeSales
/// </summary>
public class RealTimeSales
{
public long StoreID { get; set; }
public string StoreNumber { get; set; }
public decimal Value { get; set; }
}
List<RealTimeSales> salesList = new List<RealTimeSales>();
salesList = ConvertToListFromDataTable<RealTimeSales>(salesDt);
/// <summary>
/// Converts to list from data table.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt">The dt.</param>
/// <returns></returns>
public List<T> ConvertToListFromDataTable<T>(System.Data.DataTable dt)
{
System.Collections.Generic.List<T> data = new List<T>();
foreach (System.Data.DataRow row in dt.Rows)
{
T item = GetItemValue<T>(row);
data.Add(item);
}
return data;
}
/// <summary>
/// Gets the item.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dr">The dr.</param>
/// <returns></returns>
public T GetItemValue<T>(System.Data.DataRow dr)
{
System.Type temp = typeof(T);
T obj = Activator.CreateInstance<T>();
foreach (DataColumn column in dr.Table.Columns)
{
foreach (System.Reflection.PropertyInfo pro in temp.GetProperties())
{
if (pro.Name == column.ColumnName)
pro.SetValue(obj, dr[column.ColumnName], null);
else
continue;
}
}
return obj;
}