我有这样的事情:
var itemsInCart = from o in db.OrderLineItems where o.OrderId == currentOrder.OrderId select new { o.OrderLineItemId, ..., ..., o.WishListItem.Price}
有没有办法做
itemsCart.Sum() //not sure what to pass into the function
得到o.WishListItem.Price的总和还是我必须从数据库中获取另一个iQueryable
关于什么:
itemsInCart.AsEnumerable().Sum(o=>o.Price);
AsEnumerable有所不同,此查询将在本地执行(Linq To Objects).
您可以:
itemsCart.Select(C => c.Price).SUM();
只打一次db:
var itemsInCart = (from o in db.OrderLineItems where o.OrderId == currentOrder.OrderId select new { o.OrderLineItemId, ..., ..., o.WishListItem.Price} ).ToList(); var sum = itemsCart.Select(c=>c.Price).Sum();
额外的往返保存是值得的:)
尝试:
itemsCard.ToList().Select(c=>c.Price).Sum();
实际上这会表现得更好:
var itemsInCart = from o in db.OrderLineItems where o.OrderId == currentOrder.OrderId select new { o.WishListItem.Price }; var sum = itemsCard.ToList().Select(c=>c.Price).Sum();
因为您只需从数据库中检索一列.