C# List 行轉列


 1
 /*
            例子:導入  名稱,年份,每月的銷量    
            存入數據庫時:名稱-年-月-銷量
            行轉列
            
            參數說明:
              匿名類型<T> 第二個參數:前2列不動,第三個參數:傳入月份的列名
              返回 Dictionary<int, object> 類型
              剩下的就是類型轉換 


            注: 自己應用的時候請根據實際情況做好測試
            */

 

static void Main(string[] args)
 2         {
 3 
 4 var ceshi = new List<CeshiRowToCol>(){
 5                 new CeshiRowToCol(){ Type="紅細胞", Year =2020,One=10,Two=20,Three=30,Four=40 },
 6                 new CeshiRowToCol(){Type="紅細胞",Year=2021,One=12,Two=22,Three=32,Four=42 },
 7                 new CeshiRowToCol(){Type="紅細胞",Year=2022,One=13,Two=23,Three=33,Four=43 },
 8             };
 9             string Month = string.Empty;
10             var listData = RowToCol<CeshiRowToCol>(ceshi, 2, Month);
11 }
12 
13 
14 
15  private static Dictionary<int,object> RowToCol<T>(List<T> lists, int Columns, string Month)
16         {
17             //提取不變的列的列名
18             Dictionary<int, string> dicCol = new Dictionary<int, string>();
19             int i = 0;
20             foreach (var col in lists.FirstOrDefault().GetType().GetProperties())
21             {
22                 if (i < Columns)
23                 {
24                     var col1 = col.Name;
25                     dicCol.Add(i++, col1);
26                 }
27             }
28             dicCol.Add(i++, "Month");
29 
30             //返回實體
31             int z = 0;
32             Dictionary<int, object> obj = new Dictionary<int, object>();//字典
33             foreach (var row in lists)
34             {
35                 foreach (var col in row.GetType().GetProperties())
36                 {
37                     var Type = row.GetType().GetProperty(dicCol[0]).GetValue(row);
38                     var Year = row.GetType().GetProperty(dicCol[1]).GetValue(row);
39                     var num = new object();
40                     if (col.Name != dicCol[0] && col.Name != dicCol[1])
41                     {
42                         Month = col.Name;
43                         num = row.GetType().GetProperty(col.Name).GetValue(row);
44                         obj.Add(z++, new { Type, Year, Month, num });
45                     }
46                     
47                 }
48             }
49             return obj;
50         }
結果集:



 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM