简体   繁体   中英

How many times an object attribute is repeated in a list

I have a List<Appointment> , filled up with Appointment objects, that are made of Doctor and Patient types. Now I want to traverse my List to find out which Doctor has had the most appointments.

//Appointment objects
Appointment app1=new Appointment(doctor1, patient1);
Appointment app2=new Appointment(doctor2, patient3);
Appointment app2=new Appointment(doctor1, patient2);
Appointment app1=new Appointment(doctor3, patient4);

//All of the appointments are stored in this list 
List<Appointment>AllAppointments=new List<Appointment>();

//method for traversing the list
public void MostAppointments()
{
  //This returns an error: At least one obj must implement IComparable
  string find=AllAppointments.Max(x=>x.Doctor).ToString();
}

Doctor is a probably a complex object, not a numeric value, so Max won't work on it. Your also using it wrong. Max returns the maximum single value in an Enumerable but you want the most number of occurrences of a value.

I'm assuming your Doctor objects have an Id property or something similiar. You could then do:

var doctor = AllAppointments.GroupBy(a => a.Doctor.Id) //group on the doctor
    .OrderByDescending(d => d.Count()) // order by the number of instances if the same doctor 
    .First() //grab the first one

If doctor is just a string you can take the.Id out of the GroupBy

I have tried below code and working fine, you can use this:

//Appointment Class
    class Appointment
        {
            public string Doctor { get; set; }
            public string Patient { get; set; }
        }

static void Main(string[] args)
    {
        List<Appointment> appointments = new List<Appointment>();
        appointments.Add(new Appointment
        {
            Doctor = "doctor1",
            Patient = "patient1"
        });
        appointments.Add(new Appointment
        {
            Doctor = "doctor2",
            Patient = "patient1"
        });
        appointments.Add(new Appointment
        {
            Doctor = "doctor2",
            Patient = "patient2"
        });
        appointments.Add(new Appointment
        {
            Doctor = "doctor2",
            Patient = "patient3"
        });
        appointments.Add(new Appointment
        {
            Doctor = "doctor3",
            Patient = "patient1"
        });

        var result = appointments.GroupBy(x => x.Doctor).OrderByDescending(x=>x.Count()).Select(x=>x.Key).FirstOrDefault(); //doctor2


    }

Hope it will helps you.

Thanks

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM