Reputation: 5717
Following scenario:
public class Data
{
public Data()
{
Details = new List<Details>();
}
public List<Details> Details {get; set;}
}
public class Details
{
public Details()
{
}
public decimal A {get; set;}
public decimal B {get, set;}
}
Later in the code:
Data dt = new Data();
Details det = new Details();
det.A = 2;
dt.Details.Add(det); // add X amount of details to the list
.........
Now the list will look like this:
Item 1: A = 2 , B = 0
Item 2: A = 2 , B = 0
Item 3: A = 2 , B = 0
Item 4: A = 2 , B = 0
.....
Item N: A = 2 , B = 0
How can I calculate the B property value like this:
Basically:
Item 1 A is the starting point and has whatever value ...
Item 1 B value will always be the same as Item 1 A
Item 2 A can be whatever
Item 2 B = Item 1 B + Item 2 A
Item 3 A can be whatever
Item 3 B = Item 2 B + Item 3 A
and so forth.
How can I iterate through the list and automatically calculate the B property value of the items?
Upvotes: 0
Views: 92
Reputation: 46947
This should do it:
var prev = new Details();
foreach (var item in dt.Details)
{
item.B = item.A + prev.B;
prev = item;
}
Upvotes: 1
Reputation: 6486
It seems you just need a running sum stored into each variable. To do this, just modify a normal running sum approach and store it into the detail
.
decimal currentSum = 0;
for (int i = 0; i < detailList.Count; i++)
{
var detail = detailList[i];
currentSum += detail.A;
detail.B = currentSum;
}
Since you mentioned that you are not making this calculation often (your list does not change frequently), this should more than handle the job.
Upvotes: 0