Last active
December 15, 2015 04:18
-
-
Save axrwkr/5200097 to your computer and use it in GitHub Desktop.
expression visitor example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Linq.Expressions; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ModifyExpression | |
{ | |
class Program | |
{ | |
private static DateBox dtpDateStart; | |
private static DateBox dtpDateEnd; | |
private static TextBox txtDescription; | |
static void Main(string[] args) | |
{ | |
dtpDateStart = new DateBox { Value = new DateBox.HasDate { Date = DateTime.Now } }; | |
dtpDateEnd = new DateBox { Value = new DateBox.HasDate { Date = DateTime.Now.AddDays(2) } }; | |
txtDescription = new TextBox() { Text = "Hello World" }; | |
var filter = Filter(); | |
Console.WriteLine(filter); | |
Console.ReadLine(); | |
} | |
private static Expression<Func<Entity.Modelos.Flux, bool>> Filter() | |
{ | |
var dateStart = dtpDateStart.Value.Date; | |
var dateEnd = dtpDateEnd.Value.Date; | |
var description = txtDescription.Text; | |
Expression<Func<Entity.Modelos.Flux, bool>> expr = null; | |
expr = f => f.DatFlux >= dateStart.Date && f.DatFlux <= dateEnd.Date; | |
if (description != String.Empty) | |
{ | |
//add filter | |
Expression<Func<Entity.Modelos.Flux, bool>> other = f => f.Description == description; | |
var modifier = new MyVisitor(); | |
expr = (Expression<Func<Entity.Modelos.Flux, bool>>)modifier.Modify((Expression)expr, (LambdaExpression)other); | |
} | |
return expr; | |
} | |
} | |
public class MyVisitor : ExpressionVisitor | |
{ | |
private LambdaExpression visitor; | |
public Expression Modify(Expression expression, LambdaExpression visitor) | |
{ | |
this.visitor = visitor; | |
return Visit(expression); | |
} | |
protected override Expression VisitBinary(BinaryExpression b) | |
{ | |
var binary = visitor.Body as BinaryExpression; | |
return Expression.MakeBinary(ExpressionType.AndAlso, b, binary, b.IsLiftedToNull, b.Method); | |
} | |
} | |
public class TextBox | |
{ | |
public string Text { get; set; } | |
} | |
public class DateBox | |
{ | |
public HasDate Value; | |
public class HasDate | |
{ | |
public DateTime Date { get; set; } | |
} | |
} | |
} | |
namespace Entity.Modelos | |
{ | |
public class Flux | |
{ | |
public DateTime DatFlux { get; set; } | |
public string Description { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment