[英]Remove an item from a list
為什么我不能選擇刪除或刪除? 我想從列表中刪除一條記錄
IEnumerable<StockLocation_Table> AllCurrentStocklocations = db.StockLocation_Table.ToList();
List<StockLocation> StockLocations = ServerHelper.GetStockLocationsBatch(BatchUrl, i, batchSize);
foreach (StockLocation_Table _stock_table in AllCurrentStocklocations)
{
foreach (StockLocation _stock in StockLocations)
{
if (_stock.ServerLocationId == _stock_table.ServerLocationId)
{
AllCurrentStocklocations.?? why cant i say remove._stock_table
}
}
}
因為它是IEnumerable<T>
和Remove
方法沒有定義IEnumerable<T>
由於使用的是ToList
只使用一個List<T>
為類型:
List<StockLocation_Table> AllCurrentStocklocations = db.StockLocation_Table.ToList();
編輯:同樣你也不能在foreach循環中修改集合,可以改用LINQ:
var AllCurrentStocklocations = db.StockLocation_Table
.Where(x => !StockLocations
.Any(s => s.ServerLocationId == x.ServerLocationId).ToList()
您要在此處執行的操作是從數據庫表中獲取ID不在此其他列表中的所有項。 您在這里應該做的是構造一個查詢,使您只獲得沒有這些ID的那些項目,而不是將整個數據庫表下拉到一個列表中,然后遍歷每個項目的另一個列表以查找ID,以便您可以從此列表中刪除當前項目。 除了是超級低效的,這也將意味着去除收集的項目被迭代,這將打破迭代器。 而是編寫一些可以轉換為數據庫查詢的內容:
List<StockLocation> stockLocations = ServerHelper.GetStockLocationsBatch(
BatchUrl, i, batchSize);
var locationIDs = stockLocations.Select(location => location.ServerLocationId);
db.StockLocation_Table.Where(item =>
!locationIDs.Contains(item.ServerLocationId));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.