-
March 06, 2009 by bcherry
Custom .NET Collection Filters with C# Extension Methods
Have you ever had a collection (it doesn’t matter what kind of collection), and done some filtering on it using LINQ methods? For example, the following:
List<product> products = GetAllProducts();
var inStock = products.Where(p => p.Qty > 0);
foreach(Product p in inStock)
{
//dosomething with the products
}This is a pretty common usage of the LINQ extension method Where(). The above would work for any collection type, including List<>, IList<>, IEnumerable<>, IQueryable<>, or any collection with those handy LINQ extensions.
Anyways, it turns out you can actually write your own extension methods! Check this out:
public static IEnumerable<product> WhereInStock(this IEnumerable<product> p)
{
return p.Where(x => x.Qty > 0);
}//… skip ahead to some code where we use the above
var products = GetAllProducts();
var inStock = products.WhereInStock();Ok, so that’s pretty cool. But the really neat thing this lets you do is chaining:
foreach(Product p in GetProducts().WhereInStock().WhereOnSale())
{
//do something
}Of course, this method will let me grab all of the products, but filter them down based on their qty and their sale status. The real benefit here is separation of concerns. This code may be used in the UI layer somewhere. The UI coder doesn’t need to know how to determine if a product is on sale (it could be a complicated calculation), and he shouldn’t need to. By building a common set of filter methods for your domain objects, you’ll make life a lot easier for other team members.
Note: I haven’t actually compiled this code above, let me know if I made a typo!
Here’s more on implementing extension methods
[this post cross-posted with permission from bcherry.net]
- Filed under: C#
Leave a Comment