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<Dictionary<string, object>> DatatoTable(DataTable dt) { List<Dictionary<string, object>> list = new List<Dictionary<string, object>>(); 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<string, object> result = new Dictionary<string, object>(); foreach (DataColumn dc in ) { (, dr[dc].ToString()); } (result); } return list; }
public class TabletoList { public static List<T> TableToListModel<T>(DataTable dt) where T : new() { // Define the collection List<T> ts = new List<T>(); // 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!