I have a program as follows:
var toppers = new List<Student>();
var students = new List<Student>
{
new Student(){Name = "A", Marks = 90, Gender = 'M'},
new Student(){Name = "B", Marks = 80, Gender = 'M'},
new Student(){Name = "C", Marks = 70, Gender = 'M'},
new Student(){Name = "D", Marks = 60, Gender = 'F'},
new Student(){Name = "E", Marks = 100, Gender = 'F'},
};
var student = new Student();
foreach (var stdnt in students)
{
if (stdnt.Marks >= 75)
{
student.Marks = stdnt.Marks;
student.Name = stdnt.Name;
toppers.Add(student);
}
}
foreach (var stdnt in toppers)
{
Console.WriteLine(stdnt.Name + "\t" + stdnt.Marks);
}
Console.ReadKey();
The output I get is E 100 printed 3 times. I know how to fix it but don't know the problem with this way of implementation. Can someone please help.
Thanks