2014-08-29 96 views
2

我正在寫循環內寫入數據表的循環,但它會產生重複項。我不確定這裏可能會遇到什麼問題。 I「m到處重複的ID從這個API,因爲這循環循環內部循環在DataTable中創建重複C#

var users = api.Users.GetAllUsers(); 

using (DataTable table = new DataTable()) 
{ 
    var properties = users.Users[0].GetType().GetProperties(); 

    for (int i = 0; i < properties.Count(); i++) 
    { 
     table.Columns.Add(properties[i].Name, typeof(String)); 
    } 

    foreach (var user in users.Users) 
    { 
     DataRow newRow = table.NewRow(); 
     for (int j = 0; j < properties.Count(); j++) 
     { 
      var colName = properties[j].Name; 
      newRow[colName] = user.GetType().GetProperty(colName).GetValue(user, null); 
     } 
     table.Rows.Add(newRow); 

     foreach (DataRow row in table.Rows) 
     { 
      Console.WriteLine(row["id"]); 
     } 
    } 
} 
+0

不,你沒有得到重複。您需要移動循環,將表格內容打印出循環外的表格中的插入行。這是一個微不足道的錯誤。 – Steve 2014-08-29 22:11:51

回答

4

這似乎只是一個顯示問題,您有一個嵌套的循環,你循環表中的所有行,當你添加新行這意味着你輸出的所有新行。一開始你只看到一個新創建的行,但是在第四行e第二位用戶,您正在閱讀第一行。

這修復它,移動主循環背後的內環:

foreach (var user in users.Users) 
{ 
    DataRow newRow = table.NewRow(); 
    for (int j = 0; j < properties.Count(); j++) 
    { 
     var colName = properties[j].Name; 
     newRow[colName] = user.GetType().GetProperty(colName).GetValue(user, null); 
    } 
    table.Rows.Add(newRow); 
} 

foreach (DataRow row in table.Rows) 
{ 
    Console.WriteLine(row["id"]); 
} 

順便說一句,你不需要使用using語句來爲DataTableDataSet。它不使用非託管資源。 using將以其他方式阻止您進一步處理或將其從方法中返回。但是在一個例外中,通常最好的做法是使用using -statement來實現IDisposable的所有功能。

+0

@FutureReaders注意不要認爲配置無關緊要,'DataTable'是一種特殊情況。這只是因爲DataTable實現了「IComponent」接口,它是一次性的。如果你沒有在數據表上使用IComponent.Site或者IComponent.Disposed事件(比如OP沒有),那麼就不需要處理它。 – 2014-08-29 23:58:51

1

這只是一個顯示問題的結果。你foreachConsole.WriteLine是外foreach所以它打印在每一次迭代中的所有行內,移動打印從外foreach的:。

foreach (var user in users.Users) 
{ 
    DataRow newRow = table.NewRow(); 
    for (int j = 0; j < properties.Count(); j++) 
    { 
     var colName = properties[j].Name; 
     newRow[colName] = user.GetType().GetProperty(colName).GetValue(user, null); 
    } 
    table.Rows.Add(newRow); 
} 

foreach (DataRow row in table.Rows) 
{ 
    Console.WriteLine(row["id"]); 
}