2017-07-18 69 views
1

我有一個JSON對象,我從ajax後調用中獲得,我將它映射到我的下面的Customclass對象列表中。無法將列表對象轉換爲數據表

[ObjectFilter(Param = "postdata", RootType = typeof(List<ExportToExcel8020>))] 
     public void ExportToExcel(List<ExportToExcel8020> text) 

{ 
    //List<ExportToExcel8020> rm = text.AsEnumerable().ToList(); 
    //DataTable UserDt = rm .ToDataTable(); 
    DataTable UserDt = text.ToDataTable(); 
} 

這是我的名單物體的外觀,

enter image description here

現在我想這個generic list object轉換成datatable, 我試圖通過使用下面的方法來做到這一點。但我得到它說

「System.Collections.Generic.List < ... Domain.Common.ExportToExcel8020>」不包含「ToDataTable」,沒有擴展方法的定義「ToDataTable」接受的錯誤類型的第一個參數...

「System.Collections.Generic.List < ... Domain.Common.ExportToExcel8020>」找不到(是否缺少using指令或程序集引用?)

public static DataTable ToDataTable<T>(List<T> items) 
     { 
      DataTable dataTable = new DataTable(typeof(T).Name); 

      //Get all the properties 
      PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); 
      foreach (PropertyInfo prop in Props) 
      { 
       //Setting column names as Property names 
       dataTable.Columns.Add(prop.Name); 
      } 
      foreach (T item in items) 
      { 
       var values = new object[Props.Length]; 
       for (int i = 0; i < Props.Length; i++) 
       { 
        //inserting property values to datatable rows 
        values[i] = Props[i].GetValue(item, null); 
       } 
       dataTable.Rows.Add(values); 
      } 
      //put a breakpoint here and check datatable 
      return dataTable; 
     } 

我需要它作爲datatable的原因是使用openxml並導出excel文件。

我的代碼有問題嗎?或者是我的apporach本身是錯誤的?

+2

看起來您正在嘗試創建擴展方法。你需要做'公共靜態數據表ToDataTable (這個列表項目)'。 –

回答

3

這看起來像你正試圖寫一個擴展方法。方法簽名需要具有this作爲第一個參數的關鍵字,然後第一個參數指定您正在擴展的類型(並在調用擴展方法時傳入對象的實例)。嘗試

public static DataTable ToDataTable<T>(this List<T> items) 

作爲方法簽名。

+1

謝謝@skintkingle,工作。我想添加一些信息,該方法也應該寫入一個靜態類,因爲這是一個擴展方法。 –