Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding filter expressions dynamically to an array

Tags:

c#

linq

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 };
like image 529
Tys Avatar asked Apr 15 '12 14:04

Tys


1 Answers

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();
like image 102
Justin Niessner Avatar answered Sep 18 '22 17:09

Justin Niessner