Chinh Do

Convert List<T>/IEnumerable to DataTable/DataView

2nd April 2009

Convert List<T>/IEnumerable to DataTable/DataView

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.

/// <summary>
/// Convert a List{T} to a DataTable.
/// </summary>
private 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);
    }22/

    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;
    }
}
  • 1/22/2010 – Fix to support Nullable types.

This entry was posted on Thursday, April 2nd, 2009 at 7:00 pm and is filed under Dotnet/.NET - C#, Programming. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

There are currently 26 responses to “Convert List<T>/IEnumerable to DataTable/DataView”

  1. 1 On April 5th, 2009, Weekly Link Post 88 « Rhonda Tipton’s WebLog said:

    [...] Chinh Do demonstrates how to Convert List<T>/IEnumerable to DataTable/DataView. [...]

  2. 2 On July 3rd, 2009, Joe said:

    Very cool tip.. just used that to bind my grid to custom business object.
    was searching everywhere for a way to do this that supports sorting
    :)

  3. 3 On August 7th, 2009, Johannes Rudolph said:

    I’ve written a small library myself to accomplish this task. It uses reflection only for the first time an object type is to be translated to a datatable. It emits a method that will do all the work translating an object type.

    Its blazing fast. You can find it here: http://code.google.com/p/modelshredder/

  4. 4 On November 10th, 2009, Mal said:

    I know Jeff Atwood may agree, but dude, using ‘var’ for all your declarations is annoying.

    Use it where appropriate, not as a vb/keyboard laziness.

    Otherwise, very nice.

  5. 5 On December 2nd, 2009, Coder said:

    must include using statement: using System.Reflection;

    Also, I am getting an error when trying to implement:

    DataTable myTable = new DataTable(“CurrentTable”);
    myTable = ToDataTable(svc);

    It is: The type arguments for the method cannot be inferred. Not really sure what that means. Can you post an actual implementation using the method?

  6. 6 On December 2nd, 2009, Chinh Do said:

    Hi Coder

    You need to specify the type of the list items in the call. Example:

    var persons = new List<Person>();
    DataTable myTable = ToDataTable<Person>(persons);

    Mal:

    I agree w/ you… var shouldn’t be used indiscriminately. I just learned about it when I wrote this article though… so I had to use it everywhere :-)

    Chinh

  7. 7 On December 11th, 2009, Pepcoder said:

    I have a method as follows.
    List GetServicesForLayoutFields()

    can somebody suggest how can call the method ToDataTable(List items) to convert my above list to a datatable..
    Please suggest

  8. 8 On December 16th, 2009, vsrkrishnaraju said:

    it is very nice useful code for the developers

    thanks and regards
    v.s.r.k.raju

  9. 9 On January 22nd, 2010, Marko said:

    I need this code badly but when I use it in my code I get the following error:

    DataSet does not support System.Nullable

    and it is generated on the following line:

    table.Columns.Add(property.Name, property.PropertyType);

    My code is identical to yours and I use your method in my BLL method such as:

    [DataObjectMethod(DataObjectMethodType.Select, true)]
    public DataTable GetList(string sortExpression, int maximumRows, int startRowIndex)
    {
    var records = _dc.Products.OrderBy(p => p.ProductName).ToList();
    return ToDataTable(records);
    }

    If you have any suggestions please help… :)

  10. 10 On January 22nd, 2010, Chinh Do said:

    Hi Marko:

    I’ve fixed the code in the article to support nullable types. As the error message suggests, DataSets do not support nullable types. So the fix I put in is to use the non-nullable counterpart when I encounter nullable types.

    Chinh

  11. 11 On June 24th, 2010, Venkata Koppaka said:

    Very Useful dealing with custom business objects

  12. 12 On June 24th, 2010, Chinh Do said:

    Hi Venkata: Appreciate your note. Glad this was helpful.

  13. 13 On February 8th, 2011, Allen said:

    Pretty nice! If you want to compare notes to Microsoft’s version of the same thing for use as an extension method, take a look to the following MSDN link:

    http://msdn.microsoft.com/en-us/library/bb669096(v=vs.90).aspx#4

  14. 14 On February 8th, 2011, Chinh Do said:

    Thanks for the link Allen. Will check it out. Chinh

  15. 15 On March 4th, 2011, Mark J said:

    Very nice code – came in handy at just the right time!

  16. 16 On March 15th, 2011, Daniel said:

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

  17. 17 On April 7th, 2011, Chinh Do said:

    Glad to hear that.

  18. 18 On September 27th, 2011, Saif said:

    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?

  19. 19 On May 13th, 2012, Saeed Neamati said:

    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.

  20. 20 On May 13th, 2012, Chinh Do said:

    Thanks, Saeed. Glad you found this.

  21. 21 On August 2nd, 2012, Zach said:

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

    You’re awesome!

  22. 22 On August 2nd, 2012, Chinh Do said:

    Zach: Thanks for leaving me a note. That’s great.

  23. 23 On January 26th, 2013, http://tinyurl.com/unidstack29328 said:

    “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

  24. 24 On July 23rd, 2014, tinnitus miracle system said:

    tinnitus miracle system…

    Convert List/IEnumerable to DataTable/DataView » Chinh Do…

  25. 25 On July 25th, 2014, pricespy.co.nz said:

    pricespy.co.nz…

    Convert List/IEnumerable to DataTable/DataView » Chinh Do…

  26. 26 On July 25th, 2014, look at this site said:

    look at this site…

    Convert List/IEnumerable to DataTable/DataView » Chinh Do…

Leave a Comment

*