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

Convert DataTable to List of Object

Rate me:
Please Sign up or sign in to vote.
3.86/5 (7 votes)
11 May 2016CPOL 34.2K   17   1
How to convert DataTable to List of Object

Introduction

This tip will show you how to convert a DataRow into an object with nullable properties.

Hope the code snippet below will help you.

Using the Code

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;

public static class DataTableHelper
{
        public static T ToObject<T>(this DataRow row) where T : class, new()
        {
            T obj = new T();

            foreach (var prop in obj.GetType().GetProperties())
            {
                try
                {
                    if(prop.PropertyType.IsGenericType && prop.PropertyType.Name.Contains("Nullable"))
                    {
                        if (!string.IsNullOrEmpty(row[prop.Name].ToString())) 
                            prop.SetValue(obj, Convert.ChangeType(row[prop.Name], 
                            Nullable.GetUnderlyingType(prop.PropertyType), null));
                        //else do nothing
                    }
                    else
                        prop.SetValue(obj, Convert.ChangeType(row[prop.Name], prop.PropertyType),null);
                }
                catch
                {
                    continue;
                }
            }
            return obj;
        }
        /// <summary>
        /// Converts a DataTable to a list with generic objects
        /// </summary>
        /// <typeparam name="T">Generic object</typeparam>
        /// <param name="table">DataTable</param>
        /// <returns>List with generic objects</returns>
        public static List<T> DataTableToList<T>(this DataTable table) where T : class, new()
        {
            try
            {
                List<T> list = new List<T>();

                foreach (var row in table.AsEnumerable())
                {
                    var obj = row.ToObject<T>();

                    list.Add(obj);
                }

                return list;
            }
            catch
            {
                return null;
            }
        }
 }

License

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


Written By
Chief Technology Officer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
SuggestionExplanation and best practice Pin
John Brett11-May-16 23:56
John Brett11-May-16 23:56 
Even with a tip/trick, it's useful to give some sort of indication of how the code works, and indicate any limitations.

For example, mention that it requires a parameterless constructor and writeable properties.
For example, mention that it uses uncached reflection and so might perform poorly with large datasets or inside of tight loops.

Identifying a nullable property - use this method rather than checking the name of the name of the class (which will save you from mis-interpreting my NotNullableString class)
C#
var underlyingType = Nullable.GetUnderlyingType(prop.PropertyType));
if (underlyingType != null)
{
}


Error handling: If you can't add value to the exception, don't catch it. In particular, just ignoring the fact that any error has occurred is a time bomb waiting to blow someone's code in a new and exciting way.

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.