Convert List<T>/IEnumerable to DataTable/DataView

Greetings visitor from the year 2025! You can get the source code for this from my Github repo here. Thanks for visiting.

Here’s a method to convert a generic List<T> to a DataTable. This can be used with ObjectDataSource so you get automatic sorting, etc.

using statement: using System.Reflection;
...

/// <summary>
/// Convert a List{T} to a DataTable.
/// </summary>
public DataTable ToDataTable<T>(List<T> items)
{
    var tb = new DataTable(typeof (T).Name);

    PropertyInfo[] props = typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

    foreach (PropertyInfo prop in props)
    {
        Type t = GetCoreType(prop.PropertyType);
        tb.Columns.Add(prop.Name, t);
    }

    foreach (T item in items)
    {
        var values = new object[props.Length];

        for (int i = 0; i < props.Length; i++)
        {
            values[i] = props[i].GetValue(item, null);
        }

        tb.Rows.Add(values);
    }

    return tb;
}

/// <summary>
/// Determine of specified type is nullable
/// </summary>
public static bool IsNullable(Type t)
{
    return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}

/// <summary>
/// Return underlying type if type is Nullable otherwise return the type
/// </summary>
public static Type GetCoreType(Type t)
{
    if (t != null && IsNullable(t))
    {
        if (!t.IsValueType)
        {
            return t;
        }
        else
        {
            return Nullable.GetUnderlyingType(t);
        }
    }
    else
    {
        return t;
    }
}

Chinh Do

I occasionally blog about programming (.NET, Node.js, Java, PowerShell, React, Angular, JavaScript, etc), gadgets, etc. Follow me on Twitter for tips on those same topics. You can also find me on GitHub. See About for more info.

View Comments

  • Dude!!! you are lifesaver.
    I've been trying to get this #@#$ thing to work for more than 5 hours.
    Thanks a lot!

  • This is not working when I join two table with all columns selected.

    var productsQuery = (from p in db.Products
    join c in db.Categories
    on p.Category_Id equals c.Category_Id
    where p.Vendor_Code == VendorCode
    select new { p,c });

    DataTable dt = LinqToDataTable.ToDataTable(productsQuery.ToList());

    Please suggest what to do?

  • That's why I love reflection. Understanding what goes on inside an unknown object (late-binding) is one of the most powerful programming concepts. Thanks for this nice code snippet.

  • Thanks for the code...I would have lost hours and hours trying to figure this out myself.

    You're awesome!

  • “Convert List/IEnumerable to DataTable/DataView Chinh Do” was in fact a wonderful post and also I really was in fact really happy to discover the blog post.

    I appreciate it,Hye

  • Dear Chinh Do!

    I suggest a slightly revised version of your code. As a result, you can get a datatable from an IEnumerable with values of value type and strings.

    public static DataTable ToDataTable(IEnumerable input)
    {
    DataTable dt = new DataTable(typeof(T).Name);

    PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

    if (typeof(T).IsValueType || typeof(T) == typeof(System.String))
    {
    Type t = GetCoreType(typeof(T));
    dt.Columns.Add(typeof(T).Name+"C", t);
    }
    else
    {
    foreach (PropertyInfo property in properties)
    {
    Type t = GetCoreType(property.PropertyType);
    dt.Columns.Add(property.Name, t);
    }
    }

    foreach (T item in input)
    {
    if (typeof(T).IsValueType || typeof(T) == typeof(System.String))
    {
    dt.Rows.Add(item);
    }
    else
    {
    object[] values = new object[properties.Length];
    for (int i = 0; i < properties.Length; i++)
    {
    values[i] = properties[i].GetValue(item, null);
    }
    dt.Rows.Add(values);
    }
    }
    return dt;
    }
    public static Type GetCoreType(Type t)
    {
    if (t != null && IsNullable(t))
    {
    if (!t.IsValueType) { return t; }
    else { return Nullable.GetUnderlyingType(t); }
    }
    else { return t; }
    }
    public static bool IsNullable(Type t)
    {
    return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable));
    }

Recent Posts

How to switch to a different Kubernetes context or namespace?

To list available contexts: kubectl config get-contexts To show the current context: kubectl config current-context…

2 years ago

How to ssh into Kubernetes pod

kubectl exec -it <podname> -- sh To get a list of running pods in the…

2 years ago

How to Create a Soft Symbolic Link (symlink) in Unix/Linux

# Create a soft symbolic link from /mnt/original (file or folder) to ~/link ln -s…

3 years ago

How to Configure Git Username and Email Address

git config --global user.name "<your name>" git config --global user.email "<youremail@somewhere.com>" Related Commands Show current…

3 years ago

Getting the Last Monday for Any Month with TypeScript/JavaScript

TypeScript/JavaScript function getLastMonday(d: Date) { let d1 = new Date(d.getFullYear(), d.getMonth() + 1, 0); let…

4 years ago

How to View Raw SMTP Email Headers in Outlook

I had to do some SMTP relay troubleshooting and it wasn't obvious how to view…

5 years ago