Click here to Skip to main content
15,887,683 members
Articles / Web Development / ASP.NET

Various Ways to Convert DataTable to List

Rate me:
Please Sign up or sign in to vote.
4.76/5 (16 votes)
27 Mar 2016CPOL1 min read 95.3K   18   4
This article shows 3 ways to convert a DataTable to a List in C#.

Introduction

This article explains various ways to convert a DataTable to a List in C#. There are the following 3 ways to convert a DataTable to a List.

  1. Using a Loop
  2. Using LINQ
  3. Using a Generic Method

For this example, I am creating a simple Student class like:

C#
public class Student  
{  
    public int StudentId { get; set; }  
    public string StudentName { get; set; }  
    public string Address { get; set; }  
    public string MobileNo { get; set; }  
}  

And a DataTable with some data like:

C#
DataTable dt = new DataTable("Student");  
dt.Columns.Add("StudentId", typeof(Int32));  
dt.Columns.Add("StudentName", typeof(string));  
dt.Columns.Add("Address", typeof(string));  
dt.Columns.Add("MobileNo", typeof(string));  
    //Data  
dt.Rows.Add(1, "Manish", "Hyderabad","0000000000");  
dt.Rows.Add(2, "Venkat", "Hyderabad", "111111111");  
dt.Rows.Add(3, "Namit", "Pune", "1222222222");  
dt.Rows.Add(4, "Abhinav", "Bhagalpur", "3333333333");  

Now, I will convert the receding DataTable into a List< Student > using all the preceding three methods.

Using a Loop

In this method, I am using a simple for loop; other loops can also be used.

C#
public void StudentList()  
{  
    //  DataTable dt = new DataTable("Branches");  
    DataTable dt = new DataTable("Student");  
    dt.Columns.Add("StudentId", typeof(Int32));  
    dt.Columns.Add("StudentName", typeof(string));  
    dt.Columns.Add("Address", typeof(string));  
    dt.Columns.Add("MobileNo", typeof(string));  
    //Data  
    dt.Rows.Add(1, "Manish", "Hyderabad", "0000000000");  
    dt.Rows.Add(2, "Venkat", "Hyderabad", "111111111");  
    dt.Rows.Add(3, "Namit", "Pune", "1222222222");  
    dt.Rows.Add(4, "Abhinav", "Bhagalpur", "3333333333");  
  
    List<Student> studentList = new List<Student>();  
    for (int i = 0; i < dt.Rows.Count; i++)  
    {  
        Student student = new Student();  
        student.StudentId = Convert .ToInt32 (dt.Rows[i]["StudentId"]);  
        student.StudentName = dt.Rows[i]["StudentName"].ToString();  
        student.Address = dt.Rows[i]["Address"].ToString();  
        student.MobileNo = dt.Rows[i]["MobileNo"].ToString();  
        studentList.Add(student);  
    }  
}  

By Using Linq

This is the modern approach for creating a List in C#.

C#
public void StudentListUsingLink()  
{  
    //  DataTable dt = new DataTable("Branches");  
    DataTable dt = new DataTable("Student");  
    dt.Columns.Add("StudentId", typeof(Int32));  
    dt.Columns.Add("StudentName", typeof(string));  
    dt.Columns.Add("Address", typeof(string));  
    dt.Columns.Add("MobileNo", typeof(string));  
    //Data  
    dt.Rows.Add(1, "Manish", "Hyderabad", "0000000000");  
    dt.Rows.Add(2, "Venkat", "Hyderabad", "111111111");  
    dt.Rows.Add(3, "Namit", "Pune", "1222222222");  
    dt.Rows.Add(4, "Abhinav", "Bhagalpur", "3333333333");  
    List<Student> studentList = new List<Student>();  
    studentList = (from DataRow dr in dt.Rows  
            select new Student()  
            {  
                StudentId = Convert .ToInt32 (dr["StudentId"]),  
                StudentName = dr["StudentName"].ToString(),  
                Address = dr["Address"].ToString(),  
                MobileNo = dr["MobileNo"].ToString()  
            }).ToList();       
}  

Note: The advantage of the preceding two methods is we can do something.

Using a Generic Method

This is a generic method that will convert any type of DataTable to a List (the DataTable structure and List class structure should be the same).

The following are the two functions in which if we pass a DataTable and a user defined class, it will then return the List of that class with the DataTable data.

C#
private static List<T> ConvertDataTable<T>(DataTable dt)  
{  
    List<T> data = new List<T>();  
    foreach (DataRow row in dt.Rows)  
    {  
        T item = GetItem<T>(row);  
        data.Add(item);  
    }  
    return data;  
}  
private static T GetItem<T>(DataRow dr)  
{  
    Type temp = typeof(T);  
    T obj = Activator.CreateInstance<T>();  
  
    foreach (DataColumn column in dr.Table.Columns)  
    {  
        foreach (PropertyInfo pro in temp.GetProperties())  
        {  
            if (pro.Name == column.ColumnName)  
                pro.SetValue(obj, dr[column.ColumnName], null);  
            else  
                continue;  
        }  
    }  
    return obj;  
}  

To call the preceding method, use the following syntax:

C#
List< Student > studentDetails = new List< Student >();  
studentDetails = ConvertDataTable< Student >(dt); 

Change the Student class name and dt value based on your requirements. In this case, the DataTable column's name and class property name should be the same, otherwise this function will not work properly.

Summary

In this illustration, you came to understand the various ways to convert a DataTable to a List.

License

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


Written By
Software Developer
India India
Manish Kumar Choudhary is a passionate and pragmatic software engineer specializing in web application development with ASP.NET MVC, Web API, Entity Framework, NHibernet, Angular, Backbone, HTML5, and CSS. He started programming at the age of twelve on VB.Net and fell in love with it. His dream at the time was to become a software engineer so he pursues programming both academically and professionally. He has a Bachelor of Science in Computer Application and a Master of Science in Computer Application. He has over 3.5 years’ professional experience developing web applications. Outside the software world, he enjoys photography, swimming, cricket and football. Manish is based in Hyderabad, India.

Comments and Discussions

 
QuestionPerformance Enhancement Pin
Sammuel Miranda4-Dec-17 0:38
professionalSammuel Miranda4-Dec-17 0:38 
QuestionA bit of detailing would have been great Pin
srv Saurav27-Mar-16 22:11
srv Saurav27-Mar-16 22:11 
PraiseA small addition (5 votes) Pin
Bob Stoom27-Mar-16 21:37
professionalBob Stoom27-Mar-16 21:37 

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.