Tuesday, September 8, 2009

Filtering with LINQ

I recently refactored the display of data on a web page (in a Datagrid) from using a DataSet as the source to a List. As part of the original functionality, the list of items being displayed could be filtered based on selections that the user made. I decided to take advantage of the built in LINQ extension features for Lists to accomplish the filtering. The two extensions that I leveraged were the TrueForAll and Exists extensions.


In my first scenario, I have an object (Resource) that have a sub-List of times (TimeEntries) that represent their availability within a day. I need to filter the list to include all Resources in the list where their TimeEntries are not off (e.g. not on vacation, jury duty, break, etc.) In order to build that I used the TrueForAll extension that was examining a boolean method on the Resource object as shown below:


return resources.FindAll(r => r.Entries.TrueForAll(e => e.IsRegEntry()));

Additionally, I needed to filter the list to include the Resource if at least one of their entries was an Off entry, so for that I used the Exists extension as seen below:


return resources.FindAll(r => r.Entries.Exists(e => e.IsOffEntry()));

I am continually amazed at the power of LINQ and how it can make what was once fairly complex seem so much simpler and easier to understand. If you have an opportunity to check it out, I would highly recommend it.

No comments: