using System; using System.Collections.Generic; namespace PlayingWithPredicates { //public delegate bool Predicate< T >( T obj ); public interface IQuestion { ICategory Category { get; } string Text { get; } } public interface ICategory { string Name { get; } } public interface IQuestionBank { IEnumerable< IQuestion > FindBy( Predicate< IQuestion > predicate ); } public class Question : IQuestion { public Question( ICategory category, string text ) { _category = category; _text = text; } public ICategory Category { get { return _category; } } public string Text { get { return _text; } } public override string ToString( ) { return Text; } private readonly ICategory _category; private readonly string _text; } public class Category : ICategory, IEquatable< Category > { private Category( string name ) { _name = name; } public string Name { get { return _name; } } public static readonly ICategory Math = new Category( "Math" ); public static readonly ICategory English = new Category( "English" ); public bool Equals( Category category ) { if ( category == null ) { return false; } return Equals( _name, category._name ); } public override bool Equals( object obj ) { if ( ReferenceEquals( this, obj ) ) { return true; } return Equals( obj as Category ); } public override int GetHashCode( ) { return _name.GetHashCode( ); } private readonly string _name; } public class QuestionBank : IQuestionBank { public QuestionBank( ) { _questions = new List< IQuestion >( ); _questions.Add( new Question( Category.English, "Do you like English?" ) ); _questions.Add( new Question( Category.Math, "What is 2 + 2?" ) ); _questions.Add( new Question( Category.English, "Can you spell?" ) ); _questions.Add( new Question( Category.Math, "What is 3 + 3?" ) ); } public IEnumerable< IQuestion > FindBy( Predicate< IQuestion > predicate ) { foreach ( IQuestion question in _questions ) { if ( predicate( question ) ) { yield return question; } } } private readonly IList< IQuestion > _questions; } public class PredicateDelegateFactory { public static Predicate< IQuestion > EnglishFilter = delegate( IQuestion question ) { return question.Category.Equals( Category.English ); }; public static Predicate< IQuestion > MathFilter = delegate( IQuestion question ) { return question.Category.Equals( Category.Math ); }; } public class Bootstrap { public static void Main( ) { IQuestionBank questionBank = new QuestionBank( ); Console.Out.WriteLine( "Searching for all English questions..." ); foreach ( IQuestion question in questionBank.FindBy( PredicateDelegateFactory.EnglishFilter ) ) { Console.Out.WriteLine( question ); } Console.Out.WriteLine( ); Console.Out.WriteLine( "Searching for all Math questions..." ); foreach ( IQuestion question in questionBank.FindBy( delegate( IQuestion item ) { return item.Category.Equals( Category.Math ); } ) ) { Console.Out.WriteLine( question ); } Console.In.ReadLine( ); } } }