Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove list-items with Linq when List.property = myValue

Tags:

c#

linq

I have the following code:

List<ProductGroupProductData> productGroupProductDataList = FillMyList();
string[] excludeProductIDs = { "871236", "283462", "897264" };
int count = productGroupProductDataList.Count;

for (int removeItemIndex = 0; removeItemIndex < count; removeItemIndex++)
{
   if (excludeProductIDs.Contains(productGroupProductDataList[removeItemIndex].ProductId))
   {
       productGroupProductDataList.RemoveAt(removeItemIndex);
       count--;
   }
}

Now i want to do the same with linq. Is there any way for this?

The second thing would be, to edit each List-Item property with linq.

like image 629
Sebastian Avatar asked Feb 24 '23 01:02

Sebastian


1 Answers

you could use RemoveAll.

Example:

//create a list of 5 products with ids from 1 to 5
List<Product> products = Enumerable.Range(1,5)
    .Select(c => new Product(c, c.ToString()))
    .ToList(); 
//remove products 1, 2, 3
products.RemoveAll(p => p.id <=3);

where

// our product class
public sealed class Product {
    public int id {get;private set;}
    public string name {get; private set;}

    public Product(int id, string name)
    {                 
        this.id=id;
        this.name=name;
    }
}
like image 99
Paolo Falabella Avatar answered Mar 06 '23 17:03

Paolo Falabella