Donate

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:
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:
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:
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();
        }

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.