如何使用LINQ组合(n)表达式?

时间:2017-06-12 18:29:51

标签: c# linq reflection linq-expressions

我有一个带有(n)动态生成列的网格。其中一个要求是,如果在所显示的列之一中存在非空/非零值,则仅在网格中显示行。我正在使用Infragistics XamGrid,它可以选择使用行过滤器来接受表达式作为其过滤条件。我已将我的列的键绑定到MyObject属性。

我正在尝试根据网格中的哪些列显示生成一系列表达式。这是一些伪代码,显示了我想要完成的内容

System.Linq.Expressions.Expression<Func<MyObject, bool>> expr = product =>
{
    foreach (var p in MyGrid.Columns.Where(co => co.DataType == typeof (decimal?) && co.Visibility == Visibility.Visible))
    {
        Expression<Func<MyObject, bool>> exprInner = lrnc => ((decimal?) lrnc.GetPropValue(p.Key)) != 0.0m;
        combined = System.Linq.Expressions.Expression.OrElse(combined.Body, exprInner.Body);
    }
};

1 个答案:

答案 0 :(得分:0)

非常感谢斧头和他的联系。我能够根据反射属性动态组合表达式,为我的XamGrid创建一个RowsFilter。

private RowsFilter m_rowsFilter;

private void CreateFilter()
{
    CustomComparisonCondition c = new CustomComparisonCondition();

    var predicate = PredicateBuilder.False<LineRatingNodeComparison>();
    foreach (string colKey in MyXamGrid.Columns.Where(co => co.DataType == typeof (decimal?) && co.Visibility == Visibility.Visible).Select(co => co.Key))
    {
        string tempKey = colKey;
        predicate = predicate.Or(p => p.GetPropValue(tempKey) != null && (decimal?) p.GetPropValue(tempKey) != 0.0m);
    }
    c.Expression = predicate;

    //Add the RowsFilter to one column that always exists on the grid.
    m_rowsFilter = new RowsFilter(typeof (MyObject), MyXamGrid.Columns.DataColumns["Company"]);
    m_rowsFilter.Conditions.Add(c);
    MyXamGrid.FilteringSettings.RowFiltersCollection.Add(m_rowsFilter);
}