Search code examples
c#.netdelegates

Learning C# delegates. Passing a filtering function as delegate


in my Program.cs

I declare a delegate

public delegate bool FilterDelegate(Employee emp);

I create a list of employees

 List<Employee> employees = new List<Employee>
 {
               new Employee(){ID= 1907, Name= "Mary Sue", Experience = 5},
               new Employee(){ID= 1353, Name= "Peggy Sue",  Experience = 1},
               new Employee(){ID= 1645, Name= "Gary Stu", Experience = 2},
               new Employee(){ID= 141, Name= "John Doe", Experience = 3},
               new Employee(){ID= 1033, Name= "Jimmy Smith",  Experience = 4}
      };

call the displaying function and passthe delegate

Employee.FilterAndDisplay(employees, cutOffFilter);


static bool cutOffFilter(Employee emp)
{

    return emp.Experience < 4;
}

in Employee.cs

public static void FilterAndDisplay(List <Employee> employees, FilterDelegate filter)
{
    var table = new ConsoleTable("ID", "Name", "Experience");

    foreach (var emp in employees)
    {
        if(filter(emp))
        {
            table.AddRow(emp.ID, emp.Name, emp.Experience);
        }
       
    }


    table.Write();
    Console.WriteLine(); 
}

Now this works fine as it is. But what if I want to make the number of years experience dynamic? How do I pass a variable to static bool cutOffFilter ? and then use it in if(filter(emp)) ?


Solution

  • You can use LambdaExrpessions for this: This assumes your delegate has only argument. Your example isnt clear there.

    Employee.FilterAndDisplay(employees, emp => emp.Expirience < 2);
    

    or

    Employee.FilterAndDisplay(employees, emp => 
    {
        return emp.Experience < 4;
    });
    

    or

    int minExp = 5;
    Employee.FilterAndDisplay(employees, emp => emp.Expirience < minExp );