So i was digging through some old posts of Adam's and found one where he's pointing to article on MSDN on the new language features in C# 3.0. It got me thinking about how you can bring some of those features down to C# 2.0 and I came up with the concept of a RichEnumerable. This type can be used for querying using specifications.

The interface implements the IEnumerable interface but extends it with a "Where" method.

1     public interface IRichEnumerable< T > : IEnumerable< T >
2     {
3         IEnumerable< T > Where( ISpecification< T > criteria );
4     }

The implementation so far looks like this.

 1     internal class RichEnumerable< T > : IRichEnumerable< T >
 2     {
 3         private readonly IEnumerable< T > _items;
 4 
 5         public RichEnumerable( IEnumerable< T > items )
 6         {
 7             _items = items;
 8         }
 9 
10         public IEnumerable< T > Where( ISpecification< T > criteria )
11         {
12             foreach( T item in _items )
13             {
14                 if( criteria.IsSatisfiedBy( item ) )
15                 {
16                     yield return item;
17                 }
18             }
19         }
20 
21         IEnumerator< T > IEnumerable< T >.GetEnumerator( )
22         {
23             return _items.GetEnumerator( );
24         }
25 
26         public IEnumerator GetEnumerator( )
27         {
28             return ( ( IEnumerable< T > )this ).GetEnumerator( );
29         }
30     }

This could be extended further to return a RichEnumerable from the where method instead of an IEnumerable so you can filter further.

Just a quick lunch time idea... source is provided.

comments powered by Disqus