Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Various Ways to Convert DataTable to List

0.00/5 (No votes)
27 Mar 2016 1  
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:

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:

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.

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#.

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.

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:

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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here