当List.property = myValue时,使用Linq删除列表项

Seb*_*ian 4 c# linq

我有以下代码:

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--;
   }
}
Run Code Online (Sandbox Code Playgroud)

现在我想用linq做同样的事情.这有什么办法吗?

第二件事是,使用linq编辑每个List-Item属性.

Pao*_*lla 5

你可以使用RemoveAll.

例:

//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);
Run Code Online (Sandbox Code Playgroud)

哪里

// 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;
    }
}
Run Code Online (Sandbox Code Playgroud)