Today we faced a quite simple problem that were made even simpler by the dear predicates. We had a kind of event log and wanted to filter it client side (Windows Forms) using a list of criterias. We began by implementing to filter by a number of categories.
private List<Events> FilterEventsByCategory(List<Events> events,
List<Category> categories)
{
return events.FindAll(ev =>
categories.Exists(category => category.CategoryId==ev.CategoryId));
}
The next step is to implement a couple of other filters. Do you know of a nice way to generalize these to maybe somehow not having to write one method per filter? Or at least a clean way to have a dynamic list of filters that we want to apply simultaneously.
The clients are still on framework 3.0 so no LINQ.
Update: I had a hard time deciding who I should give credit for my solution. Marc had some nice ideas and is really good at explaining them. Most probaly I would have got my answer from him if I only had explained my problem a little better. Ultimately it was the generic Filter class that cmartin provided that got me on track. The Filter class used below can be found in cmartins' answer and the User class you get to dream up yourself.
var categoryFilter = new Filter<Event>(ev => categories.Exists(category => category.CategoryId == ev.CategoryId));
var userFilter = new Filter<Event>(ev => users.Exists(user => user.UserId == ev.UserId));
var filters = new List<Filter<Event>>();
filters.Add(categoryFilter);
filters.Add(userFilter);
var eventsFilteredByAny = events.FindAll(ev => filters.Any(filter => filter.IsSatisfied(ev)));
var eventsFilteredByAll = events.FindAll(ev => filters.All(filter => filter.IsSatisfied(ev)));