Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# method accepting a predicate - does this look ok?

I'd like a method that has the following API:

//get all users with a role of admin
var users = myRepository.GetUsers(u => u.Role == Role.Admin);

Will something like this work?

IList<User> GetUsers(Func<User, bool> predicate)
{            
  var users = GetAllUsers();
  return users.Where(predicate).ToList();                                                          
} 

If so, wil I be able to specify more complex predicates such as (pseudocode):

myRepository.GetUsers(u => u.CreatedDate is upto 14 days old);
like image 859
Ben Aston Avatar asked Feb 05 '10 11:02

Ben Aston


2 Answers

That looks absolutely fine. However, if you want to use the predicate with something like LINQ to SQL, you'd want to use:

IList<User> GetUsers(Expression<Func<User, bool>> predicate)

That means the lambda expression will be converted into an expression tree instead of a delegate - and that expression tree can then be converted into SQL.

like image 192
Jon Skeet Avatar answered Oct 27 '22 01:10

Jon Skeet


Yes, this will work.

What you're telling the compiler is that you're going to pass a function that works on a User object, and returns a bool - what the function looks like is entirely up to you. You can get pretty complex nesting stuff using ors (||) and ands (&&) too, but if it gets too hard to see what the predicate is doing, you should probably consider refactoring.

But basically any lambda that takes for example u as a User object, and turns it into an expression that returns bool will work.

like image 20
Tomas Aschan Avatar answered Oct 27 '22 00:10

Tomas Aschan