• Skip to primary navigation
  • Skip to main content

Nikhil Mittal

|| Software Developer || App Developer ||

  • Home
  • About Me
  • Blog
  • Testimonials
  • Achievements
  • Portfolio
  • Interview Q&As
    • Angular – QA Series 1
    • Angular – QA Series 2
    • Angular – QA Series 3
    • Angular – QA Series 4
    • Convert Angular App to Mobile APK
    • C# TYPICAL QUESTIONS – SERIES
    • Advanced Q & A – Series 1
    • Advanced Q&A – Series 2
    • Advanced Q&A Series – 3
  • Free Video Tutorials
    • ASP.NET C#
    • C# Tutorial – In Hindi
    • C# Tutorial – English
    • C#-Advanced
    • MVC DOT NET 4.8
    • Web API Dot Net Core 3.1
    • Azure DevOps
    • HTML/CSS – In Hindi
    • SQL Developer
    • Angular 10+
    • Corporate Skills
  • Consulting
  • Contact Us

Convert Datatable to List in C#

We often return Data from SQL Server in DataTable Format and we would like to use that Datatable in code using List<object>. Below Function Converts provided Datatable into list easily. It is like an extension method to the DataTable and can be called directly to Convert it to a list.

        
public static List ConvertDataTable(this DataTable table) where T : new()
{
List list = new List();
var typeProperties = typeof(T).GetProperties().Select(propertyInfo => new
{
PropertyInfo = propertyInfo,
Type = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType
}).ToList();
foreach (var row in table.Rows.Cast<DataRow>())
        {
            T obj = new T();
            foreach (var typeProperty in typeProperties)
            {
                if (row.Table.Columns.Contains(typeProperty.PropertyInfo.Name))
                {
                    object value = row[typeProperty.PropertyInfo.Name];
                    object safeValue = value == null || DBNull.Value.Equals(value)
                        ? null
                        : Convert.ChangeType(value, typeProperty.Type);

                    typeProperty.PropertyInfo.SetValue(obj, safeValue, null);
                }
            }
            list.Add(obj);
        }
        return list;
    }
Visits: 343
  • Home
  • About Me
  • You Tube
  • LinkedIn