10

I have this example which creates 3 expressions and adds them to one array of expression. Now i'd like to know how to do the same in a loop, for a unknown number of expressions.

Expression<Func<Product, bool>> filter1 = c => c.City.StartsWith("S");
Expression<Func<Product, bool>> filter2 = c => c.City.StartsWith("M");
Expression<Func<Product, bool>> filter3 = c => c.ContactTitle == "Owner";

Expression<Func<Product, bool>>[] filterExpressions = new Expression<Func<Product, bool>>[] { filter1, filter2, filter3 };
2
  • 1
    Add them or create them? Commented Apr 15, 2012 at 14:46
  • 1
    @Arion good question. TysHTTP - It's not clear where is that you're 'stuck' here. I'm guessing it's a dynamic nature of things in some way. Commented Apr 15, 2012 at 14:49

1 Answer 1

11

Use a List instead of an Array:

var filterExpressions = new List<Expression<Func<Product, bool>>>
    { filter1, filter2, filter3 };

filterExpressions.Add(c => c.Name.StartsWith("J"));

And then if you, for some reason, need to pass the list to a method that only takes an Array you can use the ToArray() method:

var filterExpressionsArray = filterExpressions.ToArray();
Sign up to request clarification or add additional context in comments.

2 Comments

Working with expressions you'd think OP would know this - but I guess given the question as is, this is the only answer that can be given at this point.
Sorry, i already fixed it some other way. I guess i just forgot how a list could help me here. I updated my code to List.ToArray(). Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.