65.9K
CodeProject is changing. Read more.
Home

Extension Method for Generic List Collection to DataTable

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.78/5 (8 votes)

Jan 21, 2015

CPOL
viewsIcon

25530

Extension method for Generic Collection to DataTable

Introduction

This code will help you to get the Extension method for GenericType Collection List for converting them to DataTable.

Background

You must know / may not know about extension method, but using this code class file you can use it without any changes.

Using the Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;

namespace coDEalers
{
    public static class Extension
    {
        public static DataTable ListToDataTable<T>(this IList<T> data, string tableName)
        {
            DataTable table = new DataTable(tableName);

            //special handling for value types and string
            if (typeof(T).IsValueType || typeof(T).Equals(typeof(string)))
            {

                DataColumn dc = new DataColumn("Value");
                table.Columns.Add(dc);
                foreach (T item in data)
                {
                    DataRow dr = table.NewRow();
                    dr[0] = item;
                    table.Rows.Add(dr);
                }
            }
            else
            {
                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
                foreach (PropertyDescriptor prop in properties)
                {
                    table.Columns.Add(prop.Name, 
                    Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
                }
                foreach (T item in data)
                {
                    DataRow row = table.NewRow();
                    foreach (PropertyDescriptor prop in properties)
                    {
                        try
                        {
                            row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                        }
                        catch (Exception ex)
                        {
                            row[prop.Name] = DBNull.Value;
                        }
                    }
                    table.Rows.Add(row);
                }
            }
            return table;
        }
    }
}

Points of Interest

This is an easy way for getting GenericList collection to DataTable.

Usage

DataTable dt = null;
List<StateList> stateListObj = JsonConvert.DeserializeObject<List<StateList>>(hdn_stateDetails_JSON.Value);
dt = stateListObj.ListToDataTable<StateList>("dtState");