0

I have a list of doctorand patient types. I need a method that will traverse the List and get all the patients that have been treated by a particular doctor.

//Appointment objects
Appointment app1= new Appointment(doctor1, patient1);
Appointment app2= new Appointment(doctor2, patient3);
Appointment app3= new Appointment(doctor1, patient2);
Appointment app4= new Appointment(doctor3, patient4);
Appointment app1= new Appointment(zdravnik2, pacient4);
Appointment app1= new Appointment(zdravnik3, pacient2);
Appointment app1 = new Appointment(zdravnik3, pacient5);
Appointment app1 = new Appointment(zdravnik1, pacient6);
Appointment app1 = new Appointment(zdravnik2, pacient4);
Appointment app1 = new Appointment(zdravnik1, pacient4);

//The objects are stored in this list, they are added in the   constructor
List<Appointment>AllAppointments=new List<Appointment>();

//Gets all the patients that have been treated by a particular doctor
public List<Patient> HadAppointmentWith(Doctor d)
{
    //Dont know how to continue from here on
    //var find=AllAppointment.GroupBy(x=>x.Patient)
}
Wai Ha Lee
  • 7,664
  • 52
  • 54
  • 80
Simon
  • 53
  • 8

1 Answers1

0

You can use Linq extension methods:

using System.Linq;

public List<Patient> GetPatients(Doctor doctor)
{
  return AllAppointments
         .Where(appointment => appointment.Doctor == doctor)
         .Select(appointment => appointment.Patient)
         .Distinct()
         .ToList();
}

It filters the full list to get all doctors matching the required doctor.

Next it selects all the patients of this doctor.

Then it selects distinct patients in case of duplicates.

And we convert the IEnumerable<> sequence result of the Linq query to a List<Patient> for the return of the method.

Olivier Rogier
  • 8,997
  • 4
  • 12
  • 26