2009-12-15 53 views
2

我有兩個陣列列表。 一個包含文件名,另一個包含failurecount。 這些值來自後面代碼中的數據庫表。在數據表中添加兩個陣列列表

現在我想將這兩個數組列表添加到一個數據表中。 有沒有辦法做到這一點?

+0

您需要提供更多信息,TimothyP的解決方案應該使用當前信息。 – Prasad 2009-12-15 04:52:25

回答

1

你提供的信息是相當有限的,所以'我會在這裏做一個瘋狂的猜測。

var table = new DataTable(); 
table.Columns.Add("value1"); 
table.Columns.Add("value2"); 

for (int i = 0; i < arrayListOne.Count; i++) 
{ 
    var row = table.NewRow(); 
    row["value1"] = arrayListOne[i]; 
    row["value2"] = arrayListTwo[i]; 
    table.Rows.Add(row); 
} 

當然,這隻會在兩個列表具有相同長度時才起作用。

如果這不是你想要的,你將不得不添加更多信息。

3

這裏有很多錯誤。首先當然是.Net 2.0和更高版本,您應該使用ArrayLists 而不是。改爲使用通用List<T>。其次,同樣重要的是,將這些數據導入到同一個數據表中的方法是重新編寫用於生成它們的SQL,以便不使用兩個查詢,而只使用一個。最後,你沒有分享任何代碼。如果我們無法看到您使用的代碼,我們將如何幫助您解決問題?

+1

不能同意更多:-) – TimothyP 2009-12-15 04:44:36

0

是的,有很多方法可以將兩個ArrayList實例添加到一個DataTable實例。以下是一種展示如何使用編譯到.NET Framework 2.0的完整代碼示例將任意數量的ArrayList添加到一個DataTable的方法。

注意:其他人做得很好嘗試破譯你所要做的 - 我只是直接用一個完整的代碼片段來回答這個問題,以防你可以從中得到任何見解。

這真的不是一個複雜的答案 - 它只是首先設置了幾個ArrayList實例,並帶有與您的問題相關的樣本數據,並在最後提供了一個片段來測試解決方案。

請評論你在這裏找到的見解,如果有的話。謝謝。

namespace Com.StackOverflow { 

    using System.Diagnostics; 
    using System.Data; 
    using System.Collections; 

    public static class SOQuestion__Add_two_arraylists_in_a_datatable { 

     public static void AnswerQuestionDirectly() { 

      // - - - - - - - - Prelimary setup to question - - - - - - - - 

      // Sample list of filenames (3 elements in total). 
      ArrayList listFilenames = new ArrayList(new[] {@"C:\a.dat", @"C:\b.dat", @"C:\c.dat"}); 

      // Sample list of error counts (2 elements in total). 
      ArrayList listFailureCounts = new ArrayList(new[] {88,51}); 

      // - - - - - - A Direct answer to the question - - - - - - - 

      // Create DataTable structure with one column. 
      DataTable dTable = new DataTable(); 
      dTable.Columns.Add("Column 1"); 

      /* Populate DataTable with all lists at once. 
      * Note: keep appending 
      * to { array initialization list } all lists you want included 
      * in the DataTable instance. 
      */ 
      foreach (ArrayList currentList in new[] { listFilenames, listFailureCounts }) { 
       foreach (object element in currentList) 
        dTable.Rows.Add(new[] { element }); // one column per row 
      } 

      // - - - - - - - - Test it for expected counts - - - - - - - - 

      int totalExpected = listFilenames.Count + listFailureCounts.Count; 
      //Verify DataTable contains the same amount of rows. 
      Debug.Assert(dTable.Rows.Count == totalExpected); 
     } 
    } 
} 

以上回答可以被複制並粘貼到cs文件和用下面的代碼運行:using Com.StackOverflow;

SOQuestion__Add_two_arraylists_in_a_datatable.AnswerQuestionDirectly();