SoFunction
Updated on 2025-03-07

Examples of 2 methods of DataTable to List in C#

DataTable is often used in projects. Assuming that DataTable is used properly, it can not only make the program concise and useful, but also improve performance and achieve twice the result with half the effort. The List<T> class is a generic equivalent class of the ArrayList class. This class uses an array that can dynamically increase the size as needed to implement the IList<T> generic interface. This article mainly introduces two methods of converting c# DataTable to List. Let’s take a look together.

1. Write a datatable to list class directly

2. Use generics to write, more general

public List&lt;Dictionary&lt;string, object&gt;&gt; DatatoTable(DataTable dt)
{
 
    List&lt;Dictionary&lt;string, object&gt;&gt; list = new List&lt;Dictionary&lt;string, object&gt;&gt;();
    foreach (DataRow dr in )// Create a new Dictionary<string,object> for each row of information, and add each column of information in the row to the dictionary    {
        Dictionary&lt;string, object&gt; result = new Dictionary&lt;string, object&gt;();
        foreach (DataColumn dc in )
        {
            (, dr[dc].ToString());
        }
        (result);
    }
    return list;
}
public class TabletoList
    {
        public static List&lt;T&gt; TableToListModel&lt;T&gt;(DataTable dt) where T : new()
        {
            // Define the collection            List&lt;T&gt; ts = new List&lt;T&gt;();
 
            // Get the type of this model            Type type = typeof(T);
            string tempName = "";
 
            foreach (DataRow dr in )
            {
                T t = new T();
                // Get the public properties of this model                PropertyInfo[] propertys = ().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    tempName = ;  // Check whether DataTable contains this column 
                    if ((tempName))
                    {
                        // Determine whether this property has a Setter                        if (!) continue;
 
                        object value = dr[tempName];
                        if (value != )
                            (t, value, null);
                    }
                }
                (t);
            }
            return ts;
        }
    }

When using the second method, you need to pay attention to: T is a class defined by itself, and the properties in it need to correspond to the database.

Summarize

This is the end of this article about two methods of DataTable to List in C#. For more related content on C#, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!