2010-06-30 85 views
11

我有一個數據表,我想在這裏刪除一行在C#中刪除行是我的代碼它拋出我的異常數據表+使用循環

foreach (DataRow row in dt1.Rows) 
{ 
    if ((row["Name"] == "Select a Lookbook") || (row["Name"] == "Create a new Lookbook")) 
    { 
     row.Delete(); 
     dt1.AcceptChanges(); 
    } 
} 

我甚至試過,如果statment和外外for循環仍然拋出我錯誤的任何想法如何實現這一任務,這是例外我得到:

Collection was modified; enumeration operation might not execute. 

最後的工作代碼:

foreach (DataRow row in dt1.Select()) 
{ 
    if ((row["Name"] == "Select a Lookbook") || (row["Name"] == "Create a new Lookbook")) 
    { 
     row.Delete();          
    } 

} 
+1

可能重複(http://stackoverflow.com/questions/2341580/safely-removing-datarow-in-foreach) – ChrisF 2010-06-30 14:32:58

回答

17

使用dt1.Rows的相反,使用dt1.Select()

這裏的目標是不使用集合本身,而是行數不是Rows集合

+0

完全按照我的意願工作,謝謝 – Developer 2010-06-30 14:42:13

+0

@Pierre:你救了我,非常感謝你:) – Chiramisu 2011-12-12 19:55:25

9

在遍歷DataTable.Rows時創建要刪除的行的列表,然後單獨刪除它們。

非LINQ的解決方案:

List<DataRow> rowsToDelete = new List<DataRow>(); 
foreach (DataRow row in dt1.Rows) 
{ 
    if ((row["Name"] == "Select a Lookbook") || 
     (row["Name"] == "Create a new Lookbook")) 
    { 
     rowsToDelete.Add(row); 
    } 
} 
foreach (DataRow row in rowsToDelete) 
{ 
    row.Delete(); 
} 
dt1.AcceptChanges(); 

LINQ的解決方案:

List<DataRow> rowsToDelete = dt1.Rows.AsEnumerable() 
    .Where(row => (row["Name"] == "Select a Lookbook") || 
        (row["Name"] == "Create a new Lookbook")) 
    .Tolist(); 
foreach (DataRow row in rowsToDelete) 
{ 
    row.Delete(); 
} 
dt1.AcceptChanges(); 
+0

我知道這是一個很好的答案,但我有去皮埃爾的答案,因爲我相信容易做到這一點。我非常感謝你的幫助。 – Developer 2010-06-30 14:41:44

1

這就是我遇到這個問題時所做的。

  Dim index As Integer = 0 
      Dim count As Integer = resultsDT.Rows.Count - 1 
      For i As Integer = 0 To count 
       If resultsDT.Rows(index).Item("something") = "something" Then 
        resultsDT.Rows(index).Delete() 
        resultsDT.AcceptChanges() 
        index = index - 1 
       End If 

       index = index + 1 
       i = i + 1 
      Next 
的[安全刪除的DataRow在的ForEach]