Create a DataTable from a Class using reflection .

There are many solution to this problem, For this we use a technical process called Reflection.

Reflection: To dynamically create an instance  of a type, bind the type to an existing  object ad invoke its methods or access its fields and properties. If you are using attributes in your code, reflection enables you to access them.

1.Use AsEnumerable() method to support LINQ:

private List<T> ConvertToList<T>(DataTable dt)    {        var columnNames = dt.Columns.Cast<DataColumn>()            .Select(c => c.ColumnName)            .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))                        pro.SetValue(objT, row[pro.Name]);                }
                return objT;            }).ToList();
    }




Comments

Popular posts from this blog

How to use lamda expression for updating using LINQ

using session for login and logout in asp.net

How to post data in MVC using form collection for Beginners.