c# - Calculate the sum of property -


i'm trying calculate sum of property name called total grandtotal. want grandtotal calculates sum of total, how tried it:

public class itemproperties         {             public int item { get; set; }             public string description { get; set; }             public int quantity { get; set; }             public int unitprice { get; set; }             public int tax { get; set; }             public int totaltax { { return ((quantity * unitprice) * tax) /100 ; } }             public int total { { return (quantity * unitprice) + totaltax; } }              public int grandtotal             {                                 {                     foreach (var l in total) //error                         l += total;          // error                     return l;                //error                 }             }         }  

the class itemproperties added add() method 2 times likes this: (so total having different values each add)

 items.add(new itemproperties {     item = convert.toint32(lines[i]),     description = lines[i + 1],     quantity = convert.toint32(lines[i + 2]),     unitprice = convert.toint32(lines[i + 3]),     tax = convert.toint32(lines[i + 4]) }); items.add(new itemproperties {     item = convert.toint32(lines[i + 5]),     description = lines[i + 6],     quantity = convert.toint32(lines[i + 7]),     unitprice = convert.toint32(lines[i + 8]),     tax = convert.toint32(lines[i + 9]) }); 

don't worry lines variables, they're not relevant.. thing want grandtotal calculate sum of total properties.

you cannot execute foreach on not enumerable - , total property int, not ienumerable.

your grandtotal property should in class contains collection of itemproperties, code similar this:

public itemproperties[] myitems { get; set; }  public int grandtotal  {          {         var total = 0;         foreach (var item in myitems)             total += item.total;          return total;     } } 

or if wanted use linq:

public list<itemproperties> myitems { get; set; }  public int grandtotal  {     {  return myitems.sum(item => item.total); } } 

note i've kept simple , not included null checking code etc - that's exercise complete.