How can I include one expression in another expression?

后端 未结 3 1022
悲哀的现实
悲哀的现实 2021-01-21 05:07

I have a DateRange class that I\'d like to apply to an IQueryable as a where predicate, automatically using the begin and end dates and automatically using an open or closed int

3条回答
  •  野的像风
    2021-01-21 05:51

    Here's the updated Apply method created after figuring this out.

        public IQueryable Apply( IQueryable source, Expression> dateField )
        {
            Expression predicate;
            if (BeginDate.HasValue)
            {
                if (BeginInclusive)
                    predicate = Expression.GreaterThanOrEqual( dateField.Body, Expression.Constant( BeginDate, typeof(DateTime) ) );
                else
                    predicate = Expression.GreaterThan( dateField.Body, Expression.Constant( BeginDate, typeof(DateTime) ) );
                source = source.Where( Expression.Lambda>( predicate ) );
            }
            if (EndDate.HasValue)
            {
                if (EndInclusive)
                    predicate = Expression.LessThanOrEqual( dateField.Body, Expression.Constant( EndDate, typeof(DateTime) ) );
                else
                    predicate = Expression.LessThan( dateField.Body, Expression.Constant( EndDate, typeof(DateTime) ) );
                source = source.Where( Expression.Lambda>( predicate ) );
            }
            return source;
        }
    

    Next, I'll transform it into an extension method, so it can be used like:

    DateRange range;
    IQueryable q;
    q = q.WhereInDateRange( range, x => x.DateField );
    

提交回复
热议问题