Custom Where Generic Extension Method

Key points

				
					using System.Collections.Generic;
using System.Linq;
using System;

namespace MyownExtensionMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            var employees = new List<Employee>
            {
                new Employee {Name="Ashok",Salary=1000},
                new Employee {Name="Abhishek",Salary=20000},
                new Employee {Name="Abhay",Salary=15000},
                new Employee {Name="Sushant",Salary=8000},
            };

            /*This is original where...*/
            var filterEmployees = employees.Where(emp => emp.Salary > 5000);
            foreach (var emp in filterEmployees)
            {
                Console.WriteLine(emp.Name);
            }

            Console.WriteLine("==============================");
            /* Below is my extension of where method  */

            var filterExtensionWhereEmp = employees.MyWhere(emp => emp.Salary > 5000);
            foreach (var emp in filterExtensionWhereEmp)
            {
                Console.WriteLine(emp.Name);
            }

            Console.ReadLine();
        }
    }

    static class ListEmployeeExtension
    {
       public static IEnumerable<Employee> MyWhere(this List<Employee> employees,
            Predicate<Employee> predicate
            )
        {
            var list = new List<Employee>();
            foreach (var item in employees)
            {
                if (predicate(item))
                    list.Add(item);
            }
            return list;
        }
    }

    class Employee
    {
        public int Salary { get; set; }
        public string Name { get; set; }
    }
}

				
			
				
					static class ListEmployeeExtension
    {
       public static IEnumerable<T> MyWhere<T>(this List<T> employees,
            Predicate<T> predicate
            )
        {
            var list = new List<T>();
            foreach (var item in employees)
            {
                if (predicate(item))
                    list.Add(item);
            }
            return list;
        }
    }

				
			
				
					static class ListEmployeeExtension
    {
       public static IEnumerable<T> MyWhere<T>(this List<T> employees,
            Func<T,bool> predicate
            )
        {
            var list = new List<T>();
            foreach (var item in employees)
            {
                if (predicate(item))
                    list.Add(item);
            }
            return list;
        }
    }
				
			
				
					static class ListEmployeeExtension
    {
       public static IEnumerable<T> MyWhere<T>(this List<T> employees,
            Func<T,bool> predicate
            )
        {
            foreach (var item in employees)
            {
                if (predicate(item))
                    yield return item;
            }
        }
    
				
			

Leave a Comment