0

I want to do a nested loop inside a function, but the member of the 2nd loop is decided by the function argument, how to make it work? Something like this:

List<Book> listBook;
List<Employee> listEmployee;

class Book
{
    string title;
    List <string> chapters;
}

class Employee
{
    string name;
    List <string> skills;
    List <string> jobs;
}


void Loop(List<object> list, Member mem)
{
    foreach (var i in list)
    {
        foreach (var j in i.mem)
        {
            string str = (string)j;
            ..................

        }
    }
}

void Main()
{
    Loop(listBook, Book.chapters);
    Loop(listEmployee, Employee.jobs);
}
DaveG
  • 491
  • 1
  • 6
  • 19
  • 1
    not mention that passing `List` to the method which takes `List` as parameter will not work – Selvin Nov 04 '19 at 11:43
  • One approach might be to, rather than taking `List`, take `List`. Have `Book` and `Employee` both implement `IMagic` (which will have a single property of type `List`). This avoids need for reflection and runtime casting. – mjwills Nov 04 '19 at 11:50

1 Answers1

3

You could use a generic method with a delegate:

void Loop<T>(IEnumerable<T> list, Func<T, List<string>> member)
{
    foreach (var i in list)
    {
        foreach (var j in member(i))
        {
            // ...    
        }
    }
}

and use it like this:

void Main()
{
    Loop(listBook, x => x.chapters);
    Loop(listEmployee,  x => x.jobs);
}
Selvin
  • 6,598
  • 3
  • 37
  • 43