1. 程式人生 > 其它 >C# List 行轉列 返回Datatable

C# List 行轉列 返回Datatable

//自己寫一個List 行轉列 返回table的方法
        public DataTable RowToColByList<T>(List<T> list,string colName)
        {
            DataTable dt = new DataTable();
            var properties = new List<PropertyInfo>(typeof(T).GetProperties());
            //  Col1  Col2  Col3   Col4   Col5 Col6
            
// A A AB AD C 1 // B A AB A A 2 // C C C B AD 3 // Col6的值變為列名,多加了一列(name)顯示原先的列名當做行, // name 1 2 3 // Col1 A B C // Col2 A A C
// Col3 AB AB C // Col4 AD A A // Col5 C A D //第一步,先把colName對應的一列資料新增為dt的列,該列不能用重複資料,在資料庫做處理 dt.Columns.Add("name"); for (int i = 0; i < list.Count; i++) { for (int j = 0; j < properties.Count; j++) {
if (string.Equals(colName, properties[j].Name)) { dt.Columns.Add(properties[j].GetValue(list[i]).ToString()); } } } //第二步。插入資料 for (int j = 0; j < properties.Count; j++) { DataRow dr = dt.NewRow(); dr[0]= properties[j].Name; for (int i = 0; i < list.Count; i++) { dr[i + 1] = list[i].GetType().GetProperty(properties[j].Name).GetValue(list[i]); } dt.Rows.Add(dr); } return dt; }