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 }
结果集: