Problem Description:
Say, we have following LINQ Query:
We like to filter out all the tickets that has expire date and not currently selected by user. User’s selection (selected item ID) will be send to the function dynamically through the function parameter. Therefore, we want to create a expression tree which will generate a LINQ query like below:
Solution:
Let’s create the expression tree step by step:
1. Do not forget to add namespace
2. Define the column name and data type to filter
3. Initialize the Binary Expression and Lamda Expression
4. If the selected item is passed through the function parameter, keep it in the exception list and create the lambda expression dynamically based on it.
5. Now, we have everything to build the where clause
6. Return the result
Full Source Code:
Below is the full source code at a glance:
/// Assumption: Datasource should have a column "Expire_Date"
///
/// Data Value Field
/// Selected Value
///
try
{
//filtered items
string expiredDateColumnName = "Expire_Date";
ParameterExpression p = Expression.Parameter(dataSource.ElementType, "p");
MemberExpression prop = Expression.Property(p, expiredDateColumnName);
)
{
var selectedValueExpr = Expression.Constant(selectedValue, selectedValue.GetType());
//ignore selected item
MemberExpression memberExpr2 = Expression.Property(p, dataValueField);
Expression binaryExpr2 = Expression.Equal(memberExpr2, selectedValueExpr);
}
else
{
pred = Expression.Lambda(binaryExpr1, p);
}
}
catch
{
throw;
}
}
Happy Programming!!!