Skip to content

Instantly share code, notes, and snippets.

@AlexArchive
Last active August 29, 2015 14:06
Show Gist options
  • Save AlexArchive/c30193918b5a073f2a96 to your computer and use it in GitHub Desktop.
Save AlexArchive/c30193918b5a073f2a96 to your computer and use it in GitHub Desktop.
Generating expressions at runtime
var containers = new[]
{
new Container { Value = "bag" },
new Container { Value = "bed" },
new Container { Value = "car" }
};
var filteredResults =
containers.Where(container => container.Value.Contains("a"))
var containers = new[]
{
new Container { Value = "bag" },
new Container { Value = "bed" },
new Container { Value = "car" }
};
// The parameter of the lambda expression
var argument = Expression.Parameter(typeof(Container));
// The "Value" property of the previously-declared parameter
var valueProperty = Expression.Property(argument, "Value");
// The Contains method represented as an expression tree
var containsCall = Expression.Call(
// Call the method on the "Value" property.
valueProperty,
// The method you want to call on the property
typeof(string).GetMethod(
"Contains",
new[] { typeof(string) }
),
// The argument to pass to the "Contains" method.
Expression.Constant("a", typeof(string))
);
// Lambda expression to pass into the Where method
var wherePredicate =
Expression.Lambda<Func<Container, bool>>(
containsCall,
argument
);
// Invoke the Where method on the queryable object itsself
var whereCall =
Expression.Call(
typeof(Queryable),
"Where",
new[] { typeof(Container) },
containers.AsQueryable().Expression,
wherePredicate
);
var expressionResults =
containers.AsQueryable().Provider.CreateQuery<Container>(whereCall);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment