|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using Rewrite;
namespace RewriteSql {
public static class FilterBuilder {
public static Expression<Func<TEntity, bool>> Or<TEntity>( params Expression<Func<TEntity, bool>>[] args ) {
Func<TEntity, bool> p1 = null;
Func<TEntity, bool> p2 = null;
Expression<Func<TEntity, bool>> expr = e => p1( e );
SimpleRewriter rwr = new SimpleRewriter( expr );
bool noArgs = true;
foreach( var arg in args.Where( y => y != null ) ) {
noArgs = false;
rwr.ApplyOnce( FilterRule<TEntity>( e => p1( e ), e => p2( e ) || p1( e ) ) );
rwr.ApplyOnce( FilterRule( e => p2( e ), arg ) );
}
if( noArgs )
return null; // ----------->>>>>>>>>>>>>>>>>>>>
// remove p1
Expression<Func<bool,TEntity,bool>> lhs = (p, e) => p || p1( e );
Expression<Func<bool,TEntity,bool>> rhs = (p, e) => p;
rwr.ApplyOnce( new Rule( lhs, rhs));
return (Expression<Func<TEntity, bool>>)rwr.Expression;
}
public static Expression<Func<TEntity, bool>> And<TEntity>( params Expression<Func<TEntity, bool>>[] args ) {
Func<TEntity, bool> p1 = null;
Func<TEntity, bool> p2 = null;
Expression<Func<TEntity, bool>> expr = e => p1( e);
SimpleRewriter rwr = new SimpleRewriter( expr );
bool noArgs = true;
foreach( var arg in args.Where( y => y != null ) ) {
noArgs = false;
rwr.ApplyOnce( FilterRule<TEntity>( e => p1( e ), e => p2( e ) && p1( e ) ) );
rwr.ApplyOnce( FilterRule( e => p2( e), arg));
}
if( noArgs )
return null; // ----------->>>>>>>>>>>>>>>>>>>>
// remove p1
Expression<Func<bool, TEntity, bool>> lhs = ( x, e ) => x && p1( e );
Expression<Func<bool, TEntity, bool>> rhs = ( x, e ) => x;
rwr.ApplyOnce( new Rule( lhs, rhs ) );
return (Expression<Func<TEntity, bool>>)rwr.Expression;
}
public static Expression<Func<TEntity, bool>> Not<TEntity>( Expression<Func<TEntity, bool>> arg ) {
if( arg == null )
return null; // ---------->>>>>>>>>>>>>>>>>>>>>>>>
Func<TEntity, bool> p = null;
return SimpleRewriter.ApplyOnce<Func<TEntity,bool>>( e => !p( e ), FilterRule( e => p( e ), arg ) );
}
static public Rule FilterRule<TEntity>( Expression<Func<TEntity, bool>> lhs, Expression<Func<TEntity, bool>> rhs ) {
return new Rule( lhs, rhs );
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.