2

DevExpress Grid (XtraGrid) 允许网格及其组进行汇总计算。可用选项包括计数、最大值、最小值、平均值、总和、无和自定义。

有没有人有一些示例代码显示如何根据作为另一列中的值提供的权重计算加权平均列?

4

2 回答 2

3

我最终解决了这个问题,并将在此处发布我的解决方案,以防其他人发现它有用。

如果加权平均值由值和每行权重组成,则包含该值的列应将权重 GridColumn 对象分配给其 Tag 属性。然后,此事件处理程序将完成其余的工作:

private static void gridView_CustomSummaryCalculate(object sender, CustomSummaryEventArgs e)
{
    GridColumn weightColumn = ((GridSummaryItem)e.Item).Tag as GridColumn;

    if (weightColumn == null)
        return;

    switch (e.SummaryProcess)
    {
        case CustomSummaryProcess.Start:
        {
            e.TotalValue = new WeightedAverageCalculator();
            break;
        }
        case CustomSummaryProcess.Calculate:
        {
            double size = Convert.ToDouble(e.FieldValue);
            double weight = Convert.ToDouble(((GridView)sender).GetRowCellValue(e.RowHandle, weightColumn));

            ((WeightedAverageCalculator)e.TotalValue).Add(weight, size);
            break;
        }
        case CustomSummaryProcess.Finalize:
        {
            e.TotalValue = ((WeightedAverageCalculator)e.TotalValue).Value;
            break;
        }
    }
}

private sealed class WeightedAverageCalculator
{
    private double _sumOfProducts;
    private double _totalWeight;

    public void Add(double weight, double size)
    {
        _sumOfProducts += weight * size;
        _totalWeight += weight;
    }

    public double Value
    {
        get { return _totalWeight==0 ? 0 : _sumOfProducts / _totalWeight; }
    }
}

该代码假定基础列值可以通过Convert.ToDouble(object).

于 2009-02-20T14:38:32.020 回答
0

如果您在 sum 中提供自己的 lambda 表达式,您应该能够按标准 sum 对它们进行分组。我认为这应该有效:

var grouped = from item in items
orderby item.Group
group item by item.Group into grp
select new
{
Average= grp.Sum(row => row.Value * row.Weight)
};
于 2009-02-20T11:38:03.157 回答