I have a data class Student, and I have an aggregate class Students. Student has two properties of type string : Name and City.
what I want to do is have the option to choose what property to iterate using the foreach mechanism.
The code I wrote works and it's also readable and nice-looking. The main issue is performance : the line in which I use the yield keyword is probably not very efficient , but the question is how much ? is it dramatic performance hit ?
Is there a better way to achieve this functionality?
(added: i don't want to allow someone to modify the returning Student objects, so all the Linq solutions proposed aren't good here. To make it clearer , I want:
property iteration + foreach mechanism integration + Student class and the list of students are readonly.
how can i achieve that ?)
static void Main(string[] args)
{
Students students = new Students();
students.AddStudent(new Student { Age = 20, Name = "Stud1" , City="City1" });
students.AddStudent(new Student { Age = 46, Name = "Stud2" , City="City2"});
students.AddStudent(new Student { Age = 32, Name = "Stud3" , City="City3" });
students.AddStudent(new Student { Age = 34, Name = "Stud4" , City="city4" });
students.PropertyToIterate = eStudentProperty.City;
foreach (string studentCity in students)
{
Console.WriteLine(studentcity);
}
students.PropertyToIterate = eStudentProperty.Name;
foreach (string studentName in students)
{
Console.WriteLine(studentName);
}
}
public class Students :IEnumerable<object>
{
private List<Student> m_Students = new List<Student>();
private eStudentProperty m_PropertyToIterate = eStudentProperty.Name;
public eStudentProperty PropertyToIterate
{
get { return m_PropertyToIterate; }
set { m_PropertyToIterate = value; }
}
public void AddStudent(Student i_Student)
{
m_Students.Add(i_Student);
}
public IEnumerator<object> GetEnumerator()
{
for (int i = 0; i < m_Students.Count; ++i)
{
yield return (object)m_Students[i].GetType().GetProperty(PropertyToIterate.ToString()).GetValue(m_Students[i], null);
}
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
public enum eStudentProperty
{
Name,
Age,
City
}
public class Student
{
public string Name { get; set; }
public string City { get; set; }
public int Age { get; set; }
}