Adding filter expressions dynamically to an array

c#, linq

Solution

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();

Problem

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 }; ```

Original source