我需要找到具有自己的统计信息(ResultGroup 类统计信息,基于所有结果统计信息)的对象列表的最大值、最小值和平均值(统计信息)值。当我添加对象时,值很容易更新,但如果我更改或删除其中一个,那么我需要再次查找统计信息。通常会有超过 40.000 个项目,我需要它来快速操作。
有没有比遍历所有项目更好的方法?
public class ResultGroup
{
private Stats resultStats;
//I need an updated stats
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)
{
//It works ok on 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)
{
//Need to find the stats here
}
else if (e.Action == NotifyCollectionChangedAction.Replace)
{
//Need to find the stats here
}
}
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;
//Another class will fill data and set the Stats (max, min, mean)
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; }
}