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));
精彩评论