Reputation: 291
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
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)
Upvotes: 1
Views: 257
Reputation: 1062560
(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.
Upvotes: 0
Reputation: 6778
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";
Upvotes: 1