Click here to Skip to main content
15,886,059 members
Articles / Programming Languages / C#
Tip/Trick

Extension Method for Generic List Collection to DataTable

Rate me:
Please Sign up or sign in to vote.
4.78/5 (8 votes)
21 Jan 2015CPOL 24.8K   17   3
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

C#
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

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

License

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


Written By
CEO coDEalers
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionAn Alternative Approach Pin
George Swan21-Jan-15 18:06
mveGeorge Swan21-Jan-15 18:06 
GeneralThoughts Pin
PIEBALDconsult21-Jan-15 17:45
mvePIEBALDconsult21-Jan-15 17:45 
OK for a start, but what if the type is a struct? Point https://msdn.microsoft.com/en-us/library/system.drawing.point(v=vs.110).aspx[^] for instance? (Not sure about enumerations either, better test it.)


But the worst is how you use Reflection -- you do it poorly. Even the simple typeof(T) appears three times, when once will suffice.
In this case caching is hindered by .net not allowing extension methods in generic classes.
However, I still recommend caching the information you gather via Reflection, perhaps in a Dictionary<Type,PropertyDescriptorCollection>


I also recommed iterating the PropertyDescriptorCollection with a for loop rather than a foreach loop, and indexing with an integer rather than a name.
NewsMy 4 and link to an other article Pin
Jérôme VIBERT21-Jan-15 2:05
Jérôme VIBERT21-Jan-15 2:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.