DataTable
DataTable is a commonly used data table type in C#. It is similar to tables in a database and can be used to store and process data. Data in DataTable can be accessed and operated through rows and columns, each row represents a data item and each column represents a property.
Here are some common properties and methods of DataTable:
- Columns: Column collection.
- Rows: Row collection.
- NewRow(): Creates a new DataRow object.
- Load(DataReader): Load data from a DataReader object to a DataTable.
- Select(filterExpression, sortExpression): Returns a collection of rows that meet the criteria based on the specified filter conditions and sort conditions.
- Merge(DataTable): Merge two DataTables and returns a new DataTable.
List
List is a dynamic array type commonly used in C#. It can be used to store any type of data and can dynamically add or delete elements. Elements in List can be accessed and manipulated through indexes.
Here are some common properties and methods of List:
- Count: Number of elements.
- Add(item): Add an element to the end of the List.
- Insert(index, item): Insert an element at the specified position.
- Remove(item): Remove an element from the List.
- RemoveAt(index): Removes the element at the specified location.
- Contains(item): determines whether the specified element is included in the List.
1. DataTable to List
public class DtToList<T> where T : new() { /// <summary> /// datatable to list /// </summary> /// <param name="dt"></param> /// <returns></returns> public static List<T> ConvertToModel(DataTable dt) { List<T> ts = new List<T>();// Define the collection Type type = typeof(T); // Get the type of this model string tempName = ""; foreach (DataRow dr in ) { T t = new T(); PropertyInfo[] propertys = ().GetProperties();// Get the public properties of this model foreach (PropertyInfo pi in propertys) { tempName = ; if ((tempName)) { if (!) continue; object value = dr[tempName]; if (value != ) (t, value, null); } } (t); } return ts; } }
2. List to DataTable
/// <summary> /// list to datatable /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collection"></param> /// <returns></returns> public DataTable ListToDt<T>(IEnumerable<T> collection) { var props = typeof(T).GetProperties(); var dt = new DataTable(); ((p => new DataColumn(, )).ToArray()); if (() > 0) { for (int i = 0; i < (); i++) { ArrayList tempList = new ArrayList(); foreach (PropertyInfo pi in props) { object obj = ((i), null); (obj); } object[] array = (); (array, true); } } return dt; }
This is the article about the sample code of DataTable and List in C#. For more related content of DataTable and List, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!