Tuesday, October 25, 2016

Filter Data for Generic Requriements.


Filter the Data.

In a day to day life the dev come across so many new and changing requirements ,where in we the requirements are tend to change. But how many times does the dev changes the code.

After the dev writes the code if he/she looks the code the dev might get different ideas to change the code. But again it should fit the new requirements.

Lets come up with a requirements first.

Requirements.
1. Filter the List<int> to get odd numbers.
2. Filter the List<int> to get Even numbers.

if we can sit and brain strom this requirements. We can come up with code which would be feasible for future requirements too. Lets get a try now.

Lets define a Generic Class with T and a method which would take the parameters as List<T> and delegate which would filter and return the List of T items.

public static class FilterData<T>
    {
        public static  IEnumerable<T> Filter(IEnumerable<T> input,Func<T,bool> Predicate)
        {
            foreach (var item in input)
            {
                if (Predicate(item))
                {
                    yield return item;
                }
            }
        }
    }


Lets see the final Main program how does it does look like.

namespace ConsoleApplicationForCSharp
{
    class Program
    {
     
        static void Main(string[] args)
        {
            var myintList = new List<int> {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
         
            Func<int, bool> IsOdd = i => i % 2 != 0;
            Func<int, bool> IsEven = i => i % 2 == 0;

           
            var results = FilterData<int>.Filter(myintList, IsOdd);
            var results2 = FilterData<int>.Filter(myintList, IsEven);
        }
    }

    public static class FilterData<T>
    {
        public static  IEnumerable<T> Filter(IEnumerable<T> input,Func<T,bool> Predicate)
        {
            foreach (var item in input)
            {
                if (Predicate(item))
                {
                    yield return item;
                }
            }
        }
    }

 
}


The calling guy know i would be passing the list of int or string and the filter criteria as a predicate and it would filter the predicate and return the Filtered data with the help of yield.






No comments:

Post a Comment