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))
?
CodePudding user response:
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 );
CodePudding user response:
I recommend using Linq.
Add a reference at the top to include System.Linq then use Where rather than your own filter method:
using System.Linq
...
foreach (Employee emp in employees.Where(e => e.Experience < 4))
table.AddRow(emp.ID, emp.Name, emp.Experience);
...
So you can change your method to:
public static void FilterAndDisplay(List <Employee> employees, Func<Employee, bool> predecate)
{
var table = new ConsoleTable("ID", "Name", "Experience");
foreach (var emp in employees.Where(predecate))
table.AddRow(emp.ID, emp.Name, emp.Experience);
table.Write();
Console.WriteLine();
}
...
If you still want the static function with param:
static bool CutOffFilter(Employee emp, int maxExp)
{
return emp.Experience < maxExp;
}
And call your filter method as:
FilterAndDisplay(employees, e => CutOffFilter(e, 4));