Remove item from list based on condition

DELETE me picture DELETE me · Jul 19, 2010 · Viewed 113.8k times · Source

I have a struct like this:

public struct stuff
{
    public int ID;
    public int quan;
}

and want to to remove the product where ID is 1.
I'm trying this currently:

prods.Remove(new stuff{ prodID = 1});

and it's not working.

THANKS TO ALL

Answer

Noldorin picture Noldorin · Jul 19, 2010

If your collection type is a List<stuff>, then the best approach is probably the following:

prods.RemoveAll(s => s.ID == 1)

This only does one pass (iteration) over the list, so should be more efficient than other methods.

If your type is more generically an ICollection<T>, it might help to write a short extension method if you care about performance. If not, then you'd probably get away with using LINQ (calling Where or Single).