So I have a list of objects (AllCompanies), and all the objects in the list inherit from the same class (Company). And I also have a field in the class they all inherit from which is another class entirely (Employees). I want to create a list of every Employee currently active, and I have every company in a list of objects. As you can see below I have tried to simply add the Employee's field to the list, but I get an error because I am trying to convert an object to a list of employees.
public class Main()
{
List<List<Employee>> AllEmployees = new List<List<Employee>>();
List<object> AllCompanies = new List<object>() { new SmallCompany(), new LargeCompany(), new SmallCompany() };
AllCompanies.ForEach(delegate(object o)
{
// - Here's the problem.
AllEmployees.Add(o.GetType().GetField("Employees").GetValue(o));
// - Here's the problem.
});
}
class Employee
{
public string Name;
public int Age;
public Employee(string name, int age)
{
Name = name;
Age = age;
}
}
class Company
{
public List<Employee> Employees = new List<Employee>();
}
class SmallCompany : Company
{
public SmallCompany(){}
}
class LargeCompany : Company
{
public LargeCompany(){}
}
How can I do this most efficiently?
You shouldn't type the list as a list of object
types. The objects are all Company
objects, and the list should reflect that.
List<Company> AllCompanies = new List<Company>()
{
new SmallCompany(),
new LargeCompany(),
new SmallCompany()
};
That will remove the need for any of that awful reflection code that will just make life hard.
Once you have that projecting each item into a new item given a selector is easy enough to do:
var allEmployees = AllCompanies.Select(company => company.Employees);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments