I have a cart.Lines List and want to remove all items where quantity == 0
This is a list that holds collection of CartLine objects:
public class Cart
{
private IList<CartLine> lines = new List<CartLine>();
public IList<CartLine> Lines { get { return lines; } set { lines = value; } }
}
public class CartLine
{
Product Product {get; set;}
int Quantity {get; set;}
}
So something like:
cart.Lines.RemoveAll(x => x.Quantity == 0)
I only get Remove and RemoveAt, not RemoveAll !
Also can’t remove in a foreach loop, get error:
Collection was modified; enumeration operation may not execute.
I have now managed to do it with this code, surely there must be something more efficient ?
var myList = cart.Lines.ToList();
myList.RemoveAll(x => x.Quantity == 0);
cart.Lines = myList;
Okay Problem solved!Thanks guys, this here does it:
cart.Lines = cart.Lines.Where(x => x.Quantity != 0);
If Lines is a
List<T>, then the simplest way is to just write:If Lines is an
IEnumerable<T>, though, you could select the negative (as Vlad suggested) – you could also change to a list usingToList()and then doRemoveAll()but that would be overkill.UPDATE:
Since you said Lines is an
IList<T>, then you will want to select the negative and convert to a list like:Or you can conver to a
List<T>usingToList()then callRemoveAll()and then save back:Incidentally, as an FYI I timed both building a remove list and then using
Remove()vs selecting the negative usingWhere()and callingToList()and the Where/ToList combo was much faster which makes sense because both allocate memory, but the Where/ToList does a lot less memory shuffling.Here’s the timing for removing all the even numbers out of a list of 100,000 ints: