Re: Calculating Totals in Collections

Re: Calculating Totals in Collections

Old forum URL: forums.lhotka.net/forums/t/3837.aspx


RockfordLhotka posted on Thursday, November 01, 2007

Honestly though, if recalculating takes .5 seconds, then recalculating from scratch every time may be unrealistic.

Is it possible to keep a "running total"? In other words, if the parent object were notified each time a specific child's specific property was changed, could it do an incremental adjustment?

Presumably this would require knowing the previous value too - but it may be worth coming up with a way to provide that. The previous post does that with a callback to the parent - which is totally workable.

Suppose the child had a Friend/internal PreviousWeight property?

public class Child : ...
{
  private int _weight;
  private int _lastWeight;
  public int Weight
  {
    get { return _weight; }
    set { _lastWeight = _weight; _weight = value; PropertyHasChanged("Weight"); }
  }
  internal int LastWeight
  { get { return _lastWeight; } }
}

Then your collection could update the TotalWeight value by backing out the LastWeight and adding in the new Weight each time it handles PropertyChanged for Weight. That'd be a lot faster than trying to recalc from scratch every time.

Copyright (c) Marimer LLC