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

DataTable to List<> using Generics

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
4 Aug 2015CPOL1 min read 13K   7   3
Convert DataTable to List<> using Generics.

Introduction

There may be a situation when you need to convert a DataTable into List<> in C#. We will see how we can do this using Generics.

Background

Somedays ago, I had to work on a project, basically I had to add some features on that. The legacy code fetches data from database as DataTable and then converts it to a specific List<> if needed. I had to add more tables in datbase and classes to the C# code. When I had to convert all these DataTable to List<>, I got pissed off. Then tried to build something more general which will do these stuffs easily.

Convert DataTable to List<>

At first we'll take a Class Tuple to map the columns of the Object.

The Class Property Name must be same as the Column Name of the DataTable. The mapping is directly upon "Class Property Name" and "Column Name of the DataTable".

 

C++
sealed class Tuple<T1, T2>
{
    public Tuple() { }
    public Tuple(T1 value1, T2 value2) { Value1 = value1; Value2 = value2; }
    public T1 Value1 { get; set; }
    public T2 Value2 { get; set; }
}

 

 

Now we'll pass the DataTable to DataTableToList class. At first we'll get the columns mapping from the Object that passed here. And then we can find the data from DataTable by matching the mapping with that.

C#
public class DataTableToList
{
    public static List<T> Convert<T>(DataTable table)
        where T : class, new()
    {
        List<Tuple<DataColumn, PropertyInfo>> map =
            new List<Tuple<DataColumn, PropertyInfo>>();

        foreach (PropertyInfo pi in typeof(T).GetProperties())
        {
            if (table.Columns.Contains(pi.Name))
            {
                map.Add(new Tuple<DataColumn, PropertyInfo>(
                    table.Columns[pi.Name], pi));
            }
        }

        List<T> list = new List<T>(table.Rows.Count);
        foreach (DataRow row in table.Rows)
        {
            if (row == null)
            {
                list.Add(null);
                continue;
            }
            T item = new T();
            foreach (Tuple<DataColumn, PropertyInfo> pair in map)
            {
                object value = row[pair.Value1];
                if (value is DBNull) value = null;
                pair.Value2.SetValue(item, value, null);
            }
            list.Add(item);
        }
        return list;
    }
}

How to use!

I've made a library for that. You an use that.

Suppose, we have a DataTable containing Students data.

C#
<code>DataTable dtStudent = GetDataTable();

.......

static DataTable GetDataTable()
{
    // Here we create a DataTable with four columns.
    DataTable table = new DataTable();
    table.Columns.Add("Name", typeof(string));
    table.Columns.Add("Roll", typeof(string));

    // Here we add five DataRows.
    table.Rows.Add("David", "a-100");
    table.Rows.Add("Sam", "a-101");
    table.Rows.Add("Christoff", "a-102");
    table.Rows.Add("Janet", "a-103");
    table.Rows.Add("Melanie", "a-104");

    return table;
}</code>

Now, I'm not comfortable with this DataTable :) So, lets convert this dtStudent to List<Student>.

Simply call this -

<code>List<Student> listStudents = DataTableToListLib.DataTableToList.Convert<Student>(dtStudent);

//Student class
public class Student
{
    public string Name { get; set; }
    public string Roll { get; set; }
}</code>

 

License

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


Written By
Software Developer (Senior) Orion Informatics Ltd.
Bangladesh Bangladesh
Hi,
I am Abdul Ahad. I have been working on Windows technologies since 2007. Most of the time I've worked with C#, ASP.NET, WCF, MSSQL 2008. Also worked with Android, iOS, Angular js, knockout js, Action Script 3. Currently working as a Software Engineer at Orion Informatics Ltd.

Comments and Discussions

 
SuggestionAuto generate Class from Database Pin
heizi13375-Aug-15 0:49
heizi13375-Aug-15 0:49 
GeneralRe: Auto generate Class from Database Pin
Abdul Ahad Monty5-Aug-15 2:57
Abdul Ahad Monty5-Aug-15 2:57 
Suggestionmay be you can try this Pin
joyhen1231234-Aug-15 15:45
joyhen1231234-Aug-15 15:45 

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.