I need to find the value of max, min and mean (stats) of a list of objects that have their own statistics (statistics of the ResultGroup class based on all statistics of the results). When I add objects, the values are easily updated, but if I change or delete one of them, I need to find the statistics again. There will usually be over 40,000 items, and I need it to be a quick operation.
Is there a better way than going through all the elements?
public class ResultGroup
{
private Stats resultStats;
public Stats ResultStats
{
get { return resultStats; }
}
private readonly ObservableCollection<Result> results = new ObservableCollection<Result>();
public ObservableCollection<Result> Results
{
get
{
return results;
}
}
public ResultGroup()
{
this.resultStats = new Stats();
this.results.CollectionChanged += new NotifyCollectionChangedEventHandler(CollectionChanged);
}
private void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
Stats lastResultStat = this.results[this.results.Count - 1].Stat;
if (resultStats.Max < lastResultStat.Max)
resultStats.Max = lastResultStat.Max;
if (resultStats.Min > lastResultStat.Min)
resultStats.Min = lastResultStat.Min;
resultStats.Mean = (resultStats.Mean * (this.results.Count - 1) + lastResultStat.Mean) / this.results.Count;
}
else if (e.Action == NotifyCollectionChangedAction.Reset)
{
this.resultStats = StatsFactory();
}
else if (e.Action == NotifyCollectionChangedAction.Remove)
{
}
else if (e.Action == NotifyCollectionChangedAction.Replace)
{
}
}
private Stats StatsFactory()
{
Stats dataStats = new Stats();
dataStats.Max = float.MinValue;
dataStats.Min = float.MaxValue;
dataStats.Mean = 0;
return dataStats;
}
}
public class Result
{
private float[] data;
public float[] Data
{
get { return data; }
}
public Result(int lenght)
{
this.data = new float[lenght];
}
private Stats stat;
public Stats Stat
{
get { return stat; }
set { stat = value; }
}
}
public class Stats
{
public float Max { get; set; }
public float Min { get; set; }
public float Mean { get; set; }
}
source
share