简体   繁体   English

从列表中删除项目

[英]Remove an item from a list

why cant I select remove or delete? 为什么我不能选择删除或删除? I want to remove a record 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 
        }
    }
}

Because it is IEnumerable<T> and the Remove method is not defined in IEnumerable<T> .Since you are using ToList just use a List<T> as type: 因为它是IEnumerable<T>Remove方法没有定义IEnumerable<T>由于使用的是ToList只使用一个List<T>为类型:

List<StockLocation_Table> AllCurrentStocklocations = db.StockLocation_Table.ToList();

Edit: Also you can't modify the collection inside of foreach loop.You can use LINQ instead: 编辑:同样你也不能在foreach循环中修改集合,可以改用LINQ:

var AllCurrentStocklocations = db.StockLocation_Table
                    .Where(x => !StockLocations
                    .Any(s => s.ServerLocationId == x.ServerLocationId).ToList()

What you want to do here is get all of the items from your DB table where the ID is not in this other list. 您要在此处执行的操作是从数据库表中获取ID不在此其他列表中的所有项。 What you should do here is construct a query such that you get just those items without those IDs, rather than pulling down the entire DB table into a list, and then going through this other list for each item ) to look for IDs so that you can remove the current item from this list. 您在这里应该做的是构造一个查询,使您只获得没有这些ID的那些项目,而不是将整个数据库表下拉到一个列表中,然后遍历每个项目的另一个列表以查找ID,以便您可以从此列表中删除当前项目。 In addition to being super inefficient, this would also mean removing the item from a collection being iterated, which would break the iterator. 除了是超级低效的,这也将意味着去除收集的项目被迭代,这将打破迭代器。 Instead write something that can be translated into a DB query: 而是编写一些可以转换为数据库查询的内容:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM