Tuesday, April 1, 2014

Predicate Wrapper Custom Class in C#

Based from this post: Predicate Wrapper Custom Class in VB.NET, here's the equivalent classes in C#.

FindTrack class:
Code:
 public class SystemTrack
    {
        public int ID { get; set; }
        public string Author { get; set; }
        public string Title { get; set; }
        public static bool FindIndexTrackNumber(SystemTrack systrac, int searchArg)
        {
            return systrac.ID.Equals(searchArg);
        }
    }
Predicate Class:
Code:
public delegate bool PredicateWrapperDelegate<T, A>(T item, A argument);
    
    public class PredicateWrapper<T, A>
    {
        private A _argument;

        private PredicateWrapperDelegate<T, A> _wrapperDelegate;

        public PredicateWrapper(A argument, PredicateWrapperDelegate<T, A> wrapperDelegate)
        {
            _argument = argument;
            _wrapperDelegate = wrapperDelegate;
        }

        private bool InnerPredicate(T item)
        {
            return _wrapperDelegate(item, _argument);
        }

        public static implicit operator Predicate<T>(PredicateWrapper<T, A> wrapper)
        {
            return new Predicate<T>(wrapper.InnerPredicate);
        }
    }
Sample usage:
Code:
static void Main(string[] args)
        {
            int SearchNumber = 456;
            int Index;

            List<SystemTrack> SystemTracks = new List<SystemTrack>();
            SystemTracks.Add(new SystemTrack() { ID = 111, Title = "Help Me", Author = "Greg Phil" });
            SystemTracks.Add(new SystemTrack() { ID = 222, Title = "Help Me1", Author = "James Nelson" });
            SystemTracks.Add(new SystemTrack() { ID = 456, Title = "Help Me2", Author = "Tom Enigma" });
            SystemTracks.Add(new SystemTrack() { ID = 12, Title = "Help Me3", Author = "Lord Brown" });
            
            Index = SystemTracks.FindIndex(new PredicateWrapper<SystemTrack,int>(SearchNumber,SystemTrack.FindIndexTrackNumber));

            if(Index != -1)
                Console.WriteLine("Sytem Track has been found at: " + Index);
            else
                Console.WriteLine("System Track not found! ");

            Console.ReadLine();
        }

0 comments:

Post a Comment