i have a data structure like this
public class Employee
{
public string Name { get; set; }
public IEnumerable<Employee> Employees { get; private set; }
// ...
}
Now i need to loop through the complete structure and execute a method on each item.
How can i create an extension on IEnumerable for such a traverse function.
Wonderfull would be something like this
employeList.Traverse(e => Save(e), e.Employees.Count > 0);
Or is it impossible and i have to create a special method in my business logic?
Thanks a lot.
Do you mean an extension method on IEnumerable<Employee>
? That's certainly feasible:
public static void Traverse(this IEnumerable<Employee> employees,
Action<Employee> action,
Func<Employee, bool> predicate)
{
foreach (Employee employee in employees)
{
action(employee);
// Recurse down to each employee's employees, etc.
employee.Employees.Traverse(action, predicate);
}
}
This has to be in a static, non-generic, non-nested class.
I'm not sure what the predicate bit is for, mind you...
EDIT: Here's the more generalised form I think you were looking for:
public static void Traverse<T>(this IEnumerable<T> items,
Action<T> action,
Func<T, IEnumerable<T>> childrenProvider)
{
foreach (T item in items)
{
action(item);
Traverse<T>(childrenProvider(item), action, childrenProvider);
}
}
You'd then call it with:
employees.Traverse(e => Save(e), e => e.Employees);
I'm assuming your main class should be Employer
rather than Employee
.
public static class EmployerExtensions
{
public static void Traverse(this Employer employer, Action<Employee> action)
{
// check employer and action for null and throw if they are
foreach (var employee in employer.Employees)
{
action(employee);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With