开发者

c# How to add up total of protected array

I'm trying to add the complete total of all TotalPrice for the 5 inputs, when I add this:

for(x= 0; x < InputOrder.Length; ++x){
Console.WriteLine("Total is ${0}", InputOrder[x].TotalPrice++);

I get an error message when compiling:

error CS0200: Property or indexer 'System.Order.TotalPrice cannot be assigned to -- it is read only

When I write it like this it compiles and the output is correct, it just seems like there is a much better way to do it

Console.WriteLine("Total is ${0}", 
 (InputOrder[0].TotalPrice + 
  InputOrder[1].TotalPrice + 
  InputOrder[2].TotalPrice + 
  InputOrder[3].TotalPrice + 
 开发者_运维技巧 InputOrder[4].TotalPrice));

Any help would be appreciated


Console.WriteLine("Total is ${0}", InputOrder.Sum(x=>x.TotalPrice));

It's not array, it's Your InputOrder.TotalPrice which is protected


Old school:

int total = 0;
for(x= 0; x < InputOrder.Length; ++x){
    total += InputOrder[x].TotalPrice;

Console.WriteLine("Total is ${0}", total);

LINQ:

Console.WriteLine("Total is ${0}", InputOrder.Sum(item => item.TotalPrice));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜