1

我目前正在使用与此类似的函数计算几列数据。

DataTable data = RetrieveDataTable();
var value = data.Compute(
    "AVG(Important_Variable)", 
    "(Distance > 1230 and Distance < 1760) OR (Distance > 4710 and Distance < 5400)"
);

这是有效的,但速度很慢。有没有更快的方法来实现同样的目标?不同的数据类型完全可以,我没有嫁给 DataTables。

4

2 回答 2

2

我不知道您是如何填充 DataTable 的,但我刚刚想到的一种方法是在填充 DataTable 时累积元素的总和和计数(您需要计算平均值。所以像:

int sum;
int count;

for(something) //Loop that populates the data table
{
   .
   .
   var Important_Variable = Read something
   Populate(Important_Variable)
   count++;
   if((Distance > 1230 and Distance < 1760) || (Distance > 4710 and Distance < 5400))
      sum += Important_Variable;
   .
   .
}
var avg = sum/count;

这样您就不必事后运行过滤器(我很确定这是耗时的部分)。

于 2013-10-03T19:38:33.630 回答
1
  1. 将所有内容映射到 POCO 对象。
  2. 编写一个(只读)get 属性……进行计算。

这是一个 ~basic~ ORM 映射器(又名,创建你的 POCO)

为什么 DataTable 比 DataReader 快

附加使用对象其他属性的只读(获取;仅)属性。

如果您的计算是“昂贵的”,并且您阅读了不止一次,则可以使用此“可空”技巧。

public class Employee
{

    public DateTime BirthDate { get; set; }
    public DateTime HireDate { get; set; }

    TimeSpan? _difference = null;
    public TimeSpan Difference
    {
        get
        {
            TimeSpan returnValue;
            if (this._difference.HasValue)
            {
                returnValue = this._difference.Value;
            }
            else
            {
                   /* COSTLY CALCULATION HERE , ONE TIME */
                this._difference = this.HireDate.Subtract(this.BirthDate);
                   /* End COSTLY Calculation */

                returnValue = this._difference.Value;
            }
            return returnValue;
        }
    }

}
于 2013-10-03T19:25:20.847 回答