2011-12-21 116 views
0

我想從EnumerableRowCollection中刪除一個數據行。那可能嗎?。我正在使用EnumerableRowCollection而不是通用var變量來使我的上下文有意義。如何從EnumerableRowCollection中刪除DataRow <DataRow>?

EnumerableRowCollection<DataRow> results = from myRow in myDataTable.AsEnumerable() 
              where results.Field("RowNo") == 1 
              select results; 

foreach(DataRow result in results) 
{ 
    if(resultOk(result)) 
    delete result from results?? 
} 
+0

我假設你知道從EnumerableRowCollection中刪除記錄不會將其從數據存儲中刪除,對嗎? – Scottie 2011-12-21 20:24:39

回答

3

可以肯定你不能刪除你迭代使用foreach從收集要素。這只是被禁止的,會導致運行時異常。

你可能只是需要一個這樣的邏輯進入linq查詢:

EnumerableRowCollection<DataRow> results = from myRow in myDataTable.AsEnumerable() 
where myRow.Field("RowNo") == 1 && !resultOk(myRow) 
select myRow; // note that you're returning myRow, not results, like in your code 
// you need to pay attention to code samples you're providing to avoid misunderstanding 

這將返回到你,你真正想要的元素列表,而無需去除foreach迴路的元素。

+0

+1好答案。同樣值得指出的是,即使你能*刪除foreach循環中的元素,'EnumerableRowCollection ''不會提供Remove方法... – 2011-12-21 20:18:50

+0

@pako,如果萬一我有EnumerableRowCollection 結果子集,如何可以刪除該子集?我的意思是如果 EnumerableRowCollection fullresults = getResults(); EnumerableRowCollection subresults = getSubResults(); EnumerableRowCollection finalResults =全部結果 - 子結果; 該怎麼做: – user1061293 2011-12-21 20:19:47

+0

正如@djacobson上面提到的,你不能從'EnumerableRowCollection '中刪除元素。但是,您可以執行的操作是LINQ-查詢集合並從此查詢中獲取新結果以覆蓋分配給變量的先前集合。或者,如果您現在運行第一個查詢時需要刪除哪些元素,請在第一個查詢中的「where」中包含其他過濾器。 – Pako 2011-12-21 20:22:51

相關問題