Click here to Skip to main content
10,500,000 members (86,546 online)
Click here to Skip to main content

Tagged as

Converting a List to a DataTable

, 18 Jul 2011 CPOL 37.6K 21
Rate this:
Please Sign up or sign in to vote.
I wrote this because I was interested in a Q&A question which asked for exactly that. Since I quite often use DataTables to transfer data, and to display it for debugging I knocked up an extension method to do it.
Then I realized that arrays implement the IList interface... Hmm. So now, I have an Extension Method that converts any List or array based data into a DataTable.
For debugging, that's pretty useful...
So, here it is, for posterity:
public static class ExtensionMethods
    {
    /// <summary>
    /// Converts a List to a datatable
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="data"></param>
    /// <returns></returns>
    public static DataTable ToDataTable<T>(this IList<T> data)
        {
        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
        DataTable dt = new DataTable();
        for (int i = 0; i < properties.Count; i++)
            {
            PropertyDescriptor property = properties[i];
            dt.Columns.Add(property.Name, property.PropertyType);
            }
        object[] values = new object[properties.Count];
        foreach (T item in data)
            {
            for (int i = 0; i < values.Length; i++)
                {
                values[i] = properties[i].GetValue(item);
                }
            dt.Rows.Add(values);
            }
        return dt;
        }
    }

Public NotInheritable Class ExtensionMethods
    ''' <summary>
    ''' Converts a List to a datatable
    ''' </summary>
    ''' <typeparam name="T"></typeparam>
    ''' <param name="data"></param>
    ''' <returns></returns>
    <System.Runtime.CompilerServices.Extension> _
    Public Shared Function ToDataTable(Of T)(data As IList(Of T)) As DataTable
        Dim properties As PropertyDescriptorCollection = TypeDescriptor.GetProperties(GetType(T))
        Dim dt As New DataTable()
        For i As Integer = 0 To properties.Count - 1
            Dim [property] As PropertyDescriptor = properties(i)
            dt.Columns.Add([property].Name, [property].PropertyType)
        Next
        Dim values As Object() = New Object(properties.Count - 1) {}
        For Each item As T In data
            For i As Integer = 0 To values.Length - 1
                values(i) = properties(i).GetValue(item)
            Next
            dt.Rows.Add(values)
        Next
        Return dt
    End Function
End Class

License

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

Share

About the Author

OriginalGriff
CEO
Wales Wales
Born at an early age, he grew older. At the same time, his hair grew longer, and was tied up behind his head.
Has problems spelling the word "the".
Invented the portable cat-flap.
Currently, has not died yet. Or has he?

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
Maciej Los25-Dec-14 9:55
protectorMaciej Los25-Dec-14 9:55 
GeneralIList => IEnumerable Pin
Andrew Rissing1-Aug-12 5:12
memberAndrew Rissing1-Aug-12 5:12 
GeneralRe: IList => IEnumerable Pin
OriginalGriff1-Aug-12 5:25
mvpOriginalGriff1-Aug-12 5:25 
GeneralReason for my vote of 5 good one. Pin
nikhi _singh28-Feb-12 17:56
membernikhi _singh28-Feb-12 17:56 
GeneralReason for my vote of 5 coz it works:) Pin
Teju MB21-Feb-12 16:53
memberTeju MB21-Feb-12 16:53 
GeneralReason for my vote of 5 Helps in debugging, and one can conv... Pin
Eddy Vluggen7-Nov-11 22:58
memberEddy Vluggen7-Nov-11 22:58 
GeneralReason for my vote of 4 simple and useful Pin
fesh00419-Jul-11 16:46
memberfesh00419-Jul-11 16:46 
GeneralReason for my vote of 5 very well done. This is what I was l... Pin
digimanus18-Jul-11 23:05
memberdigimanus18-Jul-11 23:05 
GeneralThe reason is that years agoo in Borland Delphi I created a ... Pin
wvd_vegt18-Jul-11 23:01
memberwvd_vegt18-Jul-11 23:01 
GeneralReason for my vote of 5 Very usefull (and compact) code. A ... Pin
wvd_vegt18-Jul-11 22:38
memberwvd_vegt18-Jul-11 22:38 
GeneralRe: That is exactly what it was meant to do... Pin
OriginalGriff18-Jul-11 22:45
mvpOriginalGriff18-Jul-11 22:45 
GeneralVery usefull (and compact) code. A pity it copies data into... Pin
wvd_vegt18-Jul-11 22:37
memberwvd_vegt18-Jul-11 22:37 
GeneralReason for my vote of 5 Thanks for the code. It's very usefu... Pin
Charl Pohlmann18-Jul-11 20:22
memberCharl Pohlmann18-Jul-11 20:22 
GeneralReason for my vote of 5 very useful. nice idea! Pin
johannesnestler18-Jul-11 3:30
memberjohannesnestler18-Jul-11 3:30 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150819.1 | Last Updated 19 Jul 2011
Article Copyright 2011 by OriginalGriff
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid