Passing filtering functions to Where() in LINQ-to-SQL

Posted by Daniel on Stack Overflow See other posts from Stack Overflow or by Daniel
Published on 2010-04-28T02:32:24Z Indexed on 2010/04/28 2:43 UTC
Read the original article Hit count: 271

Filed under:

I'm trying to write a set of filtering functions that can be chained together to progressively filter a data set. What's tricky about this is that I want to be able to define the filters in a different context from that in which they'll be used. I've gotten as far as being able to pass a very basic function to the Where() clause in a LINQ statement:

filters file:

Func<item, bool> returnTrue = (i) => true;

repository file:

public IQueryable<item> getItems()
{
    return DataContext.Items.Where(returnTrue);
}

This works. However, as soon as I try to use more complicated logic, the trouble begins:

filters file:

Func<item, bool> isAssignedToUser = (i) => i.assignedUserId == userId;

repository file:

public IQueryable<item> getItemsAssignedToUser(int userId)
{
    return DataContext.Items.Where(isAssignedToUser);
}

This won't even build because userId isn't in the same scope as isAssignedToUser(). I've also tried declaring a function that takes the userId as a parameter:

Func<item, int, bool> isAssignedToUser = (i, userId) => i.assignedUserId == userId;

The problem with this is that it doesn't fit the function signature that Where() is expecting:

Func<item, bool>

There must be a way to do this, but I'm at a loss for how. I don't feel like I'm explaining this very well, but hopefully you get the gist.

Thanks,

Daniel

© Stack Overflow or respective owner

Related posts about linq-to-sql