使用LINQ删除列表中的元素

3

I have a List of type some entity

List

public class OrderLine
{
   public string productCode;
   public int quantity;


}

如果产品代码与某些产品相同,我需要从上述列表中删除项目。

List<string> ProductsToBeExcluded = new List<string>(){"1234","1237"};

那么,从 List<OrderLine> 中我需要移除等于 1234 和 1237 的产品

我尝试过:

  1. create a List<string> from List<OrderLine> using

      List<OrderLine> OrderLines = GetOrderLines();
      var ol = from o in OrderLines
            select o.ProductCode;
    

2.

  List<string> ProductsToBeExcluded = new List<string>(){"1234","1237"};
   var filtered = OrderLines.Except(ProductsToBeExcluded);

如何继续进行删除操作?
谢谢。
2个回答

8
在这种情况下,您不需要使用LINQ,而是可以直接使用List<T>.RemoveAll
OrderLines.RemoveAll(x => ProductsToBeExcluded.Contains(x.ProductCode));

2
使用接受谓词的ListRemoveAll方法。
OrderLines.RemoveAll(x => ProductsToBeExcluded.Contains(x.ProductCode));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接