views:

142

answers:

2

are there any good tutorials online for learning about the c# 2.0 language feature "predicates"?

i'm trying to learn how to use predicates along with linq to sql to modify my queries

what i am trying to do is query a table of customers and filter it based on changing criteria. for example

  • find all customers who have zipcode = 90210
  • find all customers who are male
  • find all customers who are male AND > have zipcode = 90210

right now i am doing this using if/else statements which feels pretty wrong

also, it's possible that i'll have to add other filters so i want a flexible solution to this problem that's easy to extend without breaking anything (open closed principle i think)

A: 

(btw - the lambda-based predicates used with LINQ-to-SQL are C# 3.0 / .NET 3.5, not C# 2.0)

Well, what specifically are you trying to do?

Predicates are just filters (either as a delegate or an Expression); they don't directly allow you to modify the TSQL etc, unless you combine them with functions that the LINQ-to-SQL provider can handle (these), or UDFs mapped onto your data-context as composable functions (FunctionAttribute).

At the simplest:

who are male AND > have zipcode = 90210

var qry1 = from cust in ctx.Customers
          where cust.Gender == 'M' && cust.Zip = '90210'
          select cust;

var qry2 = from cust in ctx.Customers
          where cust.Zip = '90210'
          select cust;

Or for a non-trivial example (a dynamic search form / combining separately)

IQueryable<Foo> query = ctx.Customers;
// note "gender" here is "char?" for this example
if(gender != null) query = query.Where(x=>x.Gender == (char)gender);
if(zip != null) query = query.Where(x=>x.Zip == zip);

etc

You can also build expression-based predicates by hand, but that is more work, and requires knowledge of the Expression API.

Marc Gravell
what i am trying to do is query a table of customers and filter it based on changing criteria. for examplefind all customers who have zipcode = 90210find all customers who are malefind all customers who are male AND > have zipcode = 90210right now i am using if/else which feels pretty wrong
jorsh1
sorry, didn't realize formatting doesn't work in here. i have updated my question so it's easier to read.
jorsh1
thanks mark, the query wont execute until it's tripped right? so i don't have to worry about the query being executed twice in your "combining separately" example? if so, this is EXACTLY what i was looking for!
jorsh1
+1  A: 

A predicate is simply a method with the following signature :

bool Predicate<T>(T item)

It represents a condition that can be verified or not by objects of type T.

It is use in link to filter enumerables in the .Where clause.

You can also use lambdas that return a boolean value :

item => item.Nickname == "ThinkBeforeCoding";
Think Before Coding