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 40 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 1st, 2014, Gertie said:

    Wonderful goods from you, man. I’ve understand your stuff previous
    to and you are juset extremely magnificent. I rrally like what you have acquired
    here, certainly like what you are stating and the wway in which you saay
    it. Yoou make it enjoyable and you still tale
    care of to keep it wise. I can’t wait to read far more from you.
    This is really a wonderful website.

    Here is my ssite – bàn ghế mầm non (Gertie)

  25. 25 On July 3rd, 2014, Parthenia said:

    What’s up every one, here every one is sharing such
    experience, so it’s nice to read this blog, and I used to pay a quick
    visit this website everyday.

  26. 26 On July 4th, 2014, sexercise said:

    Hey There. I found your blog using msn. This is an extremely well written article.
    I’ll make sure tto boomark it and return too read more
    of your useful information. Thans for the post. I will definitely return.

  27. 27 On July 8th, 2014, denver truck accident attorney said:

    First of all I would like to say great blog! I had a quick question which I’d like
    to ask if you don’t mind. I was interested to find
    out how you center yourself and clear your mind before writing.
    I’ve had a tough time clearing my thoughts in getting my thoughts out.
    I truly do enjoy writing but it just seems like the first 10 to 15 minutes are wasted
    simply just trying to figure out how to begin. Any
    ideas or tips? Kudos!

    Here is my weblog: denver truck accident attorney

  28. 28 On July 8th, 2014, http://progressivelibrarian.com/ said:

    I was recommended this website by way of my cousin. I’m not positive whether this
    submit is written by way of him as nobody
    else realize such detailed approximately my difficulty. You’re wonderful!

    Thanks!

    My site … escort birmingham (http://progressivelibrarian.com/)

  29. 29 On July 9th, 2014, sofa karaoke said:

    *Place: It does not need anyy special place for enjoying this hobby.
    They come under the category of acceptable pleasures and
    you really don’t hafe to thik much before makinbg a mind.
    The bar owner was another Brit that went bby the name of Paul.

    My blog post; sofa karaoke

  30. 30 On July 9th, 2014, new pc games said:

    There are various associated with motives which is often caused by this kind of undeniable
    relationship. Obviously the common income may keep adhere to Clash of Clans Hack for your near future.
    The financial media looks unable to makeup the intellect on these
    kind of concerns which unsettles buyers. For you to offer
    one of many wonderful politics experts Odysseus Bootlegger ‘The
    success associated with almost any political program
    can certainly simply genuinely end up being assessed if the extra fat female possesses sung.
    a Extremely, this individual fresh nothing of Clash of Clans Hack till
    this individual was nicely straight into the thirties.
    I am firmly that if people in politics spent fewer occasion thinking
    about Clash of Clans Hack along with set a lot more hard work to their household
    lifestyle, that any of us would likely employ a distinct
    state.

    Precisely why would Clash of Clans Hack combination the street?
    : To access the opposite area! Simply just our little tall tale, although enables desire
    which Clash of Clans Hack will not encourage comparable hilarity in the next elections.
    I believe Clash of Clans Hack should not be allowed to acquire with
    respect to the bigger issue: why are usually all of us here?

    Placing this particular apart it’s connected with
    wonderful relevance. The item determines purchase, puts out ‘fires’,
    and it provides the most beneficial out within men and women. I am going to leave the final word towards
    the famous Beyonce De Niro: My partner and i desire Clash
    of Clans Hack, nothing additional nothing at all less.

    Here is my web blog :: new pc games

  31. 31 On July 9th, 2014, Raphael said:

    The picture above is of acorns from the red oak tree. Always go for a quality mattress: In order to
    have a fine sleep you would require a fine mattress. In the mediuum range Crate & Barrel, Goldn Mitchell, and Thomasville.

    Feel free to visit my web site; sofa giường đẹp – Raphael,

  32. 32 On July 9th, 2014, hungry shark evolution hack said:

    The main topic of hungry shark evolution cheats has been protected
    intensively by the entire world press in the last few years.
    Your consistently modifying popular accept hungry shark evolution cheats displays the actual
    interesting depth with the theme. Even as it has grown a new sizzling theme for controversy, it is effect on western cinema has
    not been presented proper acknowledgement. Undoubtedly feelings
    function strong amongst the second echelons regarding gradual assistance field companies,
    exactly who form the final great a solution to the civilzation. Complex nevertheless it truly is My
    spouse and i will right now make an effort to offer
    an exaustive report about hungry shark evolution cheats
    and its particular quite a few market sectors. Despite precisely what quite a few might believe, hungry shark evolution cheats established fact all
    over many nations all over the world. hungry shark evolution cheats but has existed for a lot of hundreds of years and it has an important significance inside the existence of the many.
    It might be safe for you to believe which hungry shark evolution cheats will probably
    be all-around for a long time and have a
    huge impact on the particular existence of the
    many people. test out pertaining to introduce

    My page: hungry shark evolution hack

  33. 33 On July 10th, 2014, Bobbye said:

    The dozens of posts that are adred to the group forum each week advertise events and casual get-togethers tthat help to expand
    one’s confort zonbes in an encouraging, non- pressuring
    manner. Becwuse what fuels public singing better than alcohol.
    We also took the opportunity to try to find a machine so we could get tickets
    for the shuttle we knew we’d have to take to Holiday Park from our final train stop.

    my web page; sofa karaoke đẹp (Bobbye)

  34. 34 On July 12th, 2014, Kassie said:

    Appreciate this post. Let me try it out.

    Take a look at my web site; last minute hotels boston (Kassie)

  35. 35 On July 12th, 2014, skin lightening with lemon said:

    Hello, itts good post on the tpic of media print, we all bee familiar with
    media is a impressive soource of data.

    Here is my blog :: skin lightening with lemon

  36. 36 On July 13th, 2014, desktop wallpaper project said:

    What’s up, I wish for to subscribe for this blog to obtain hottest updates, therefore where can i
    do it please assist.

    My web-site – desktop wallpaper project

  37. 37 On July 13th, 2014, sofa giuong said:

    Yes, releasing from our ‘mind chatter’ certainly
    plays a key role in our meditation, as this ‘noise’ can distract us from our deeper, more
    centered awareness. As such, they are able to provide a good comfort level.

    In the medium range Crate & Barrel, Golden Mitchell,
    and Thomasville.

    Here is my site … sofa giuong

  38. 38 On July 18th, 2014, copysniper 2 said:

    This is the perfect website for anyone who hopes to understand this topic.
    You know a whole lot its almost hard to argue with you (not that I actually would want to…HaHa).

    You definitely put a brand new spin on a subject that has been discussed for a long time.

    Wonderful stuff, just wonderful!

  39. 39 On July 19th, 2014, Http://storify.com/ said:

    An impressive share! I have just forwarded this
    onto a co-worker who had been doing a little homework on this.
    And he actually ordered me breakfast because I discovered
    it for him… lol. So let me reword this…. Thanks for the meal!!
    But yeah, thanks for spending some time to discuss this subject here
    on your blog.

    My website: plastic Surgery In denver (Http://storify.com/)

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

    tinnitus miracle system…

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

Leave a Comment

*