Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing items in List using LINQ [duplicate]

Tags:

c#

linq

I have a List of type some entity

List

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


}

i need to remove items from the above List if the productCode is equal to some products.

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

so, from List<OrderLine> i need to remove products which are equal to 1234 and 1237

i have tried

  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);

how do I proceed further in removing

thanks

like image 909
CSharped Avatar asked Jan 17 '26 23:01

CSharped


2 Answers

In this case you don't need LINQ but can just use List<T>.RemoveAll instead

OrderLines.RemoveAll(x => ProductsToBeExcluded.Contains(x.ProductCode));
like image 97
JaredPar Avatar answered Jan 20 '26 14:01

JaredPar


Use RemoveAll method of List which accepts predicate

OrderLines.RemoveAll(x => ProductsToBeExcluded.Contains(x.ProductCode));
like image 28
Kamil Budziewski Avatar answered Jan 20 '26 13:01

Kamil Budziewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!