Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traversing a list, execute a method: Extension possible?

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.

like image 831
Khh Avatar asked Feb 27 '23 15:02

Khh


2 Answers

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);
like image 191
Jon Skeet Avatar answered Mar 01 '23 17:03

Jon Skeet


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);
        }
    }
}
like image 21
Kent Boogaart Avatar answered Mar 01 '23 15:03

Kent Boogaart