代码之家  ›  专栏  ›  技术社区  ›  Drew Noakes

如何将加权平均摘要添加到devexpress xtragrid?

  •  2
  • Drew Noakes  · 技术社区  · 15 年前

    devexpress网格(xtragrid)允许网格及其组进行汇总计算。可用选项有count、max、min、avg、sum、none和custom。

    是否有人获得了一些示例代码,说明如何根据另一列中作为值提供的权重计算加权平均列?

    2 回复  |  直到 13 年前
        1
  •  3
  •   Drew Noakes    15 年前

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

    如果加权平均值由每行的值和权重组成,则包含该值的列应将weight 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) .

        2
  •  0
  •   Tim Cooper    13 年前

    如果在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)
    };
    
    推荐文章