【发布时间】:2011-10-06 04:41:56
【问题描述】:
我有一个 cart.Lines 列表,想删除数量 == 0 的所有项目
这是一个包含 CartLine 对象集合的列表:
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;}
}
比如:
cart.Lines.RemoveAll(x => x.Quantity == 0)
我只得到 Remove 和 RemoveAt,而不是 RemoveAll!
也不能在 foreach 循环中删除,得到错误: 收藏已修改;枚举操作可能无法执行。
我现在已经设法用这段代码做到了,肯定有更有效的东西吗?
var myList = cart.Lines.ToList();
myList.RemoveAll(x => x.Quantity == 0);
cart.Lines = myList;
好的,问题解决了!谢谢大家,这里就可以了:
cart.Lines = cart.Lines.Where(x => x.Quantity != 0);
【问题讨论】:
-
看起来 ToList()/RemoveAll() 组合甚至可能是最有效的......(见下面的时间安排),但几乎没有。否定条件下的 Where() 后跟 ToList() 几乎一样快。我认为 RemoveAll() 对 List
进行了非常优化,因此它非常快,而其他 Linq 方法使用迭代器(yield return)往往会慢一些。