I want to provide a set of filters for the user to select, and each filter will correspond to Expression<Func<X, bool>> . Thus, I could take a dynamic list of available elements ("Joe", "Steve", "Pete", etc.) and create a set of "hard-coded" filters based on these names and let the user choose which filter he wants to use . My problem is that even when I try to βhardcodeβ my expression based on a string value from a dynamic list, the expression still saves the value as, it seems to me, a property that hangs an anonymous type (and I donβt know how to serialize anon. Type). Sorry if this is confusing, I'm not quite sure how to articulate it.
Here is my sample code:
public class Foo { public string Name { get; set; } } static void Main(string[] args) { Foo[] source = new Foo[] { new Foo() { Name = "Steven" } , new Foo() { Name = "John" } , new Foo() { Name = "Pete" }, }; List<Expression<Func<Foo, bool>>> filterLst = new List<Expression<Func<Foo, bool>>>(); foreach (Foo f in source) { Expression<Func<Foo, bool>> exp = x => x.Name == f.Name; filterLst.Add(exp); } } }
My problem is that when I look, when I look at the body of my expression, it reads as follows:
(x.Name = value(ConsoleApplication1.Program+<>c__DisplayClass3).value)
When what I really want, for the first we read like this:
(x.Name = "Steven")
(if I change my code to this, instead, exactly what I get:
Expression<Func<Foo, bool>> exp = x => x.Name == "Steven";
)
I tried to force my value to a local string value before inserting it into the expression, but it doesn't seem to help:
List<Expression<Func<Foo, bool>>> filterLst = new List<Expression<Func<Foo, bool>>>(); foreach (Foo f in source) { string value = f.Name; Expression<Func<Foo, bool>> exp = x => x.Name == value; filterLst.Add(exp); }
I donβt understand why (or indeed even how) it is still looking at some kind of anonymous type, even when I use a local variable declared in a string. Is there any way to make this work the way I want it?