c# - How to get Balance from property -


i have 1 class contains simple data transactions 1 field amount holds transaction amount plus or minus, question how calculate balance after each transaction without using linq, want know how done in merely pure programming.

this code transaction class:

using system;  namespace accountsummary {     class mastertransdata     {         public long transno { get; set; }         public datetime transdate { get; set; }         public long accountno { get; set; }         public decimal amount { get; set; }          public decimal getbalance()         {             decimal[] balance;             mastertransdata[] mtd = transdata();             for(int i=0; i<mtd.length; i++)             {                 balance[i] += mtd[i].amount;              }              return balance;         }     } } 

presumably balance single value total amounts, not array.

you asked solution without linq, thought may useful show how relates. in linq, use sum extension method:

mastertransdata[] mtd = transdata(); var balance = mtd.sum(x => x.amount); 

sum isn't particularly magic. once has projected items ienumerable<decimal> then, internally, doing this:

decimal sum = 0; foreach (decimal v in source)  {     sum += v; } return sum; 

so imperative way of writing code be:

mastertransdata[] mtd = transdata(); decimal balance = 0; foreach (var d in mtd)  {     balance += d.amount; } return balance; 

what linq adds mix that's preferable separates intent implementation. improves readability. can @ 2 line example , 'ok, we're summing amounts'. if want know what's going on in more detail, can drill down , inspect method doing. alternative reading 6 lines of code , having reason it's doing.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -