2017-02-21 59 views
1

我有一個XML,我已經使用了LINQ to XML。因爲我想捕獲一些元素/屬性數據,所以我將它們放在一個字符串數組中。後來我用foreach循環將這些值從字符串數組插入到DataRow中;因爲我的最終目標是從中獲取DataTable。LINQ DataRow的結果

以下是我的代碼

System.Data.DataTable dt = new System.Data.DataTable(); 

    dt.Columns.Add("col_1"); 
    dt.Columns.Add("col_2"); 
    dt.Columns.Add("col_3"); 
    string[] arr = new string[3]; 

    var myData = from n in doc.Descendants("product") 
      select new string[]{ 
       arr[0] = n.Attribute("name").Value, 
       arr[1] = n.Attribute("prodid").Value, 
       arr[2] = n.Attribute("price").Value 
      }; 

    foreach (var item in myData) 
    { 
     dt.Rows.Add(item[0],item[1],item[2]); 
    } 

是否可以將這些結合起來,並直接得到LINQ查詢,而不是使用的foreach輸出作爲數據表?

而不是select new string[]我可以使用類似select new DataTableDataTable的實例嗎?

我知道我的表結構應該是固定的。

更新

感謝@CodingDawg & @Rahul辛格,我現在想知道這兩者之間的最佳方法。

我會檢查我的樣本數據來比較相同。

但是從您的經驗來看,考慮到大數據(10000個元素=> 10000行)哪個更好?

+0

您是否嘗試過在加載XML到DataSet?你應該從中得到一個可用的DataTable。 – tinstaafl

+0

@tinstaafl - 由於涉及到一些步驟,我無法直接將XML加載到DataSet中。另外,還想檢查上面的一個是否可行。 – A3006

回答

0

使用LINQ的.ToList()的ForEach()函數

System.Data.DataTable dt = new System.Data.DataTable(); 

dt.Columns.Add("col_1"); 
dt.Columns.Add("col_2"); 
dt.Columns.Add("col_3"); 

doc.Descendants("product") 
      .ToList() 
      .ForEach(
       n => dt.Rows.Add(n.Attribute("name").Value, 
           n.Attribute("prodid").Value, 
           n.Attribute("price").Value)); 
+0

我不知道我們可以有.ForEach是這樣的。謝謝。爲此+1。 – A3006

3

有辦法整個XML加載到數據集,但我想你需要一些特定的值,也需要做一些自定義過濾或充塞因此您使用LINQ到XML,您可以直接投影的數據表,而不使用的foreach循環像這樣: -

DataTable myData = doc.Descendants("product") 
         .Select(x => 
         { 
          var row = dt.NewRow(); 
          row.SetField<string>("col_1", (string)x.Attribute("name")); 
          row.SetField<string>("col_2", (string)x.Attribute("prodid")); 
          row.SetField<string>("col_1", (string)x.Attribute("price")); 
          return row; 
         }).CopyToDataTable(); 

myData將舉行最終數據表。

+0

謝謝,我會試試這個。 – A3006