2017-06-21 437 views
1

我有一個Dictionary<string, AFValues>其中AFValues是一個AFValue類型對象的集合。如何將Dictionary <string,List <object>>轉換成C#中的DataTable?

什麼是字典數據結構的幕後快照: enter image description here

Value每個Key有這個AFValues集合: enter image description here

那麼,這是我至今寫將字典轉換爲數據表。

private DataTable dataTable = null;  
private DataTable ConvertToDataTable(Dictionary<string, AFValues> dict) 
     { 
      using (dataTable = new DataTable()) 
      { 
       if (dict.Count > 0) 
       { 
        var headers = dict.Keys; 
        foreach (var colHeader in headers) 
        { 
         dataTable.Columns.Add(colHeader); 
        } 

        foreach (var row in dict) 
        { 
         DataRow dataRow = dataTable.NewRow(); 
         foreach (var afVal in row.Value) 
         { 
          dataRow[row.Key] = afVal.Value; 
         } 
         dataTable.Rows.Add(dataRow); 
        } 
       } 
      } 
      return dataTable; 
     } 

基礎上,dict.Keys這是相當簡單的我已經成功地創建了DataTable列。但是,我的問題在於如何正確循環通過AFValues並將每個AFValue映射到其相應的列(dict.Key)?

我已經完成了我的研究,但是找不到與我的相同的任何相關方案。

這是返回的DataTable根據上面的代碼是不正確的。

enter image description here

這應該是預期的輸出(樣本表)

enter image description here

任何幫助不勝感激。

+1

您不能使用'using'塊。如果你離開你的使用塊,DataTable將被丟棄。 – PinBack

+0

@PinBack感謝您的支持。你是對的。我不需要'使用'塊,因爲我需要返回結果。 – Juniuz

回答

2

您可以使用一個代碼塊這樣你的內循環:

for (int i = 0; i < dict.Values.Max(item => item.Count()); i++) 
{ 
    DataRow dataRow = dataTable.NewRow(); 

    foreach (var key in dict.Keys) 
    { 
     if (dict[key].Count > i) 
      dataRow[key] = dict[key][i]; 
    } 
    dataTable.Rows.Add(dataRow); 
} 
+0

這一個作品像一個魅力,謝謝你,真的很感激它。 – Juniuz

相關問題