[英]Performance of a loop within a collection parent record
I want to make my classes a bit smarter.我想让我的课更聪明一点。 So I am adding to a sub-list which is a child of
DocumentLines
and I have Documents
.所以我要添加到一个子列表,它是
DocumentLines
的子列表,我有Documents
。 Consider them to be like OrderHeader
, OrderLines
.将它们视为像
OrderHeader
, OrderLines
。 The reason why I call them documents was that I am using status to tell what type of order it is.我称它们为文档的原因是我使用状态来判断它是什么类型的订单。
I want to have a property in my class that will get the current items in the child list and sum the cost up so I have a property I can bind to in my form.我想在我的 class 中有一个属性,它将获取子列表中的当前项目并将成本相加,因此我有一个可以在我的表单中绑定的属性。 Is below ok or could it become too exhaustive if I have to say 20 products on an order?
如果我必须在订单上说 20 种产品,以下是否可以,或者是否会变得过于详尽?
public List<DocumentLines> Items;
public decimal OrderTotal
{
get
{
decimal price = 0.00m;
foreach (var item in Items)
{
price += item.LinePrice;
}
return price;
}
}
It won't be too exhaustive.它不会太详尽。 It will be fine.
没事的。 You could consider using the LINQ
Sum()
method .您可以考虑使用 LINQ
Sum()
方法。
public List<DocumentLines> Items;
public decimal OrderTotal
{
get
{
return Items.Sum(item => item.LinePrice);
}
}
With C# 6 you can use expression-bodied members (=>) to shorten it further.使用 C# 6 您可以使用表达式主体成员(=>) 进一步缩短它。
public List<DocumentLines> Items;
public decimal OrderTotal => Items.Sum(item => item.LinePrice);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.