Click here to Skip to main content
15,914,419 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
See more:
How to write data type conversion extended method in c#?
Have any way to convert data table data into list or model class? Please provided with sample code.
Posted

Hi

Use this Utility for converting Datatable to Generic List

If your DataTable Column is not same as the Class Property Name u can use the attribute to match the column.
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Reflection;

namespace  Helper
{
    public class GenericUtility
    {
        public static List<t> DataTableToList<t>(DataTable dt) where T : class, new()
        {
            List<t> lstItems = new List<t>();
            if (dt != null && dt.Rows.Count > 0)
                foreach (DataRow row in dt.Rows)
                    lstItems.Add(ConvertDataRowToGenericType<t>(row));
            else
                lstItems = null;
            return lstItems;
        }

        private static T ConvertDataRowToGenericType<t>(DataRow row) where T : class,new()
        {
            Type entityType = typeof(T);
            T objEntity = new T();
            foreach (DataColumn column in row.Table.Columns)
            {
                object value = row[column.ColumnName];
                if (value == DBNull.Value) value = null;
                PropertyInfo property = entityType.GetProperty(column.ColumnName, BindingFlags.Instance | BindingFlags.IgnoreCase | BindingFlags.Public);
                try
                {
                    if (property != null && property.CanWrite)
                        property.SetValue(objEntity, value, null);
                    else
                    {
                        property = entityType.GetProperties().Where(k => k.GetCustomAttributes(typeof(SQLInfoAttribute), true).Length > 0).SingleOrDefault(k => ((SQLInfoAttribute)k.GetCustomAttributes(typeof(SQLInfoAttribute), true)[0]).ColumnName == column.ColumnName);
                        if (property != null)
                            property.SetValue(objEntity, value, null);
                    }
                }
                catch (Exception ex)
                {
                    string exceptionMessageInfo_Names = string.Format("SQL Column Name:= {0} \n BusinessType Property Name:= {1}", column.ColumnName, property != null ? property.Name : string.Empty);
                    string exceptionMessageInfo_DataTypes = string.Format("SQL Column Type:= {0} \n BusinessType Property Type:= {1}", column.DataType, property != null ? property.PropertyType.Name : string.Empty);
                    throw new Exception("Error Message := " + ex.Message + Environment.NewLine + exceptionMessageInfo_Names +
                    Environment.NewLine + exceptionMessageInfo_DataTypes);
                }
            }
            return objEntity;
        }
    }

    [AttributeUsage(AttributeTargets.Property)]
    public class SQLInfoAttribute : Attribute
    {
        public string ColumnName;
        public SQLInfoAttribute(string columnName) { ColumnName = columnName; }

    }
}
 
Share this answer
 
v2
see this
Extension Methods for Data Type Conversion
and to Convert data table into list
C#
Try 
List<object> lst = dt.AsEnumerable().ToList<object>();
// or 
IEnumerable<object> something= dt.AsEnumerable();
 
Share this answer
 
v3
See this for examples and ready to go solutions:


http://dotnetext.codeplex.com/[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900