I want to define a collection with an enumerator that can be set at run time.
I defined an enumerator:
public class JuniorEmployeeEnumerator : IEnumerable<Employee> {
List<Employee> list = new List<Employee>();
public JuniorEmployeeEnumerator(List<Employee> emplist) {
list = emplist;
}
public IEnumerator<Employee> GetEnumerator() {
for (int i = 0; i < list.Count; i++) {
if (list[i].Age < 50) {
yield return list[i];
}
}
}
IEnumerator IEnumerable.GetEnumerator() {
return (GetEnumerator());
}
}
And the collection accepts the enumerator:
public class EmployeeCollection : IEnumerable<Employee> {
public List<Employee> Employees { get; set; }
public IEnumerable<Employee> EnumeratorType { get; set; }
public EmployeeCollection() {
Employees = new List<Employee>();
}
public IEnumerator<Employee> GetEnumerator() {
return EnumeratorType.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator() {
return (GetEnumerator());
}
}
So, the usage should be as:
static void Main(string[] args) {
EmployeeCollection empcoll = new EmployeeCollection();
empcoll.Employees.Add(new Employee("Fatima", 57));
empcoll.Employees.Add(new Employee("Evangeline", 52));
empcoll.Employees.Add(new Employee("Damien", 49));
empcoll.Employees.Add(new Employee("Cameroon", 55));
empcoll.Employees.Add(new Employee("Babu", 24));
Console.Write("Senior Employees \n");
empcoll.EnumeratorType = new JuniorEmployeeEnumerator(empcoll.Employees);
foreach (Employee anEmp in empcoll.GetEnumerator()) {
Console.Write(" " + anEmp.Name + " " + anEmp.Age + "\n");
}
Console.ReadKey();
}
But i get this compilation error:
foreach statement cannot operate on variables of type 'System.Collections.Generic.IEnumerator' because 'System.Collections.Generic.IEnumerator' does not contain a public definition for 'GetEnumerator'
How can I fix it?