c# DataGrid BindingListCollectionView 自定义过滤器抛出聚合函数的无效用法意味着

c# DataGrid BindingListCollectionView custom filter throwing invalid usage of aggregate function mean

我有一个集合视图,我想在其中应用大于平均值的过滤器。 问题是列类型是字符串。 所以正常大于任何数字在转换为 double 类型后工作完美,问题是如何做到平均。 我尝试了以下代码:

collectionView.CustomFilter = $"CONVERT({col}, 'System.Double') > AVG([{col}])";

正如预期的那样,由于 AVG 无法应用于字符串类型,它中断了。但是当我试图把

AVG([CONVERT({col}, 'System.Double')])

它不评估转化。

有什么克服它的建议吗?

这实际上是底层 DataView.RowFilter(和 DataColumn.Expression)支持的限制 Aggregates:

An aggregate can only be applied to a single column and no other expressions can be used inside the aggregate.

我看到克服它的唯一方法是将(动态)计算列添加到执行 CONVERT 的基础 DataTable,然后在过滤器表达式中使用该列。

像这样:

var dataView = collectionView.SourceCollection as DataView;
if (dataView.Table.Columns[col].DataType == typeof(string))
{
    var calcCol = col + "_Double";
    if (!dataView.Table.Columns.Contains(calcCol))
        dataView.Table.Columns.Add(calcCol, typeof(double), $"CONVERT({col}, 'System.Double')");
    col = calcCol;
}
collectionView.CustomFilter = $"{col} > AVG({col})";