I trying to write an application that has a collection of students using different types of collections (List, ArrayList, Dictionary)
Requirements:
- Use C# Iterators (not FOREACH)
- Return IEnumerable of Students
I created a class called Students implementing IEnumerable interface
I have 3 methods for each collection and each returning an IEnunerable of Students
public class Students : IEnumerable
{
//Generic List
public IEnumerable getList()
{
List<string> ListStudents = new List<string>();
ListStudents.Add("Bob");
ListStudents.Add("Nancy");
for (int i = 0; i < ListStudents.Count; i++)
{
yield return ListStudents[i];
}
}
//Generic Dictionary
public IEnumerable getDiction()
{
Dictionary<string, string> DicStudents = new Dictionary<string, string>();
DicStudents.Add("FirstName", "Nana");
for (int i = 0; i < DicStudents.Count; i++)
{
yield return DicStudents.Values.ToList()[i];
}
}
//Array List
public IEnumerable getArray()
{
ArrayList ArrayStudents = new ArrayList { "Tom", "Noah", "Peter" };
for (int i = 0; i < ArrayStudents.Count; i++)
{
yield return ArrayStudents[i];
}
}
public IEnumerator GetEnumerator()
{
}
}
How do I take the 3 collections above and iterate through them as if there were one collection. At the moment, I am putting them into an Array but I cannot seem to iterate through them:
public class GetALL: IEnumerable
{
public IEnumerator GetEnumerator()
{
Students s = new Students();
IEnumerator[] enumerator = new IEnumerator[3]
{
s.getList().GetEnumerator(),
s.getDiction().GetEnumerator(),
s.getArray().GetEnumerator(),
};
return enumerator[3];
}
}
There must be an easier way or a way that it can actually be donw….
Thanks
🙂
Ok I misunderstood the request.
I have the below:
public class Student : IEnumerable
{
int ID;
string Name;
string Phone;
public IEnumerable<Student> getStudentList()
{
List<Student> e = new List<Student>();
e.Add(new Student() { Name = "Bob", ID = 20, Phone = "914-123-1234" });
e.Add(new Student() { Name = "Jack", ID = 21, Phone = "718-123-1234" });
e.Add(new Student() { Name = "Nancy", ID = 22, Phone = "212-123-1234" });
for (int i = 0; i < e.Count; i++)
{
yield return e[i];
}
}
public IEnumerator GetEnumerator()
{
}
}
How do I return the List of Students and write them to the console? I want to keep my list of students in the Student Object and then iterate through them object and print the list of students?
Is this possible?
OK, now your
Studentclass is really messed up. AS it is defined, each Student has a list of Students within it.You will be needing three classes here:
A Students class – Which you will probably want do implement IList (and probably derived from List
A Program class, which will contain your Main() method, and will hold you Students object, and will have the method responsible for putting the Student objects into the Students object.
Also, note that a List is also an IEnumerable, so your code:
Is exactly the same as: