C#: Predicates in LINQ to Entities

If you started programming MVC, in particular the Entity Framework Model, and find yourself filtering your data model using the Where<TSource>() method, you should know by now that you can chain this method instead of using the query syntax.

// using query syntax - calling Where method once
carQuery.Where(c => c.Color == 'red' && c.Price < 10000);

// using method chaining - calling Where method multiple times
carQuery.Where(c => c.Color == 'red').Where(c => c.Price < 10000);

// method chaining is useful in a loop
foreach (KeyValuePair<string, string> filter in filters)
string filterVal = filter.Value;
switch (filter.Key)
case "Color":
carQuery = carQuery.Where(c => c.Color == filterVal).
case "Price":
int price = Int32.Parse(filterVal);
carQuery = carQuery.Where(c => c.Price < price).


There are other ways to do predicates but  are more advance topic than the ones mentioned above.  The links below talks about them:


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s