我有一个List<Appointment>
,充满了Appointment
和Doctor
类型的Patient
对象。
现在,我想遍历我的清单,以找出哪个医生的约会最多。
//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();
}
答案 0 :(得分:2)
医生可能是一个复杂的对象,而不是数字值,因此Max无法对其进行操作。您还用错了。 Max返回Enumerable中的最大单个值,但是您希望出现最多的值。
我假设您的Doctor对象具有ID属性或类似内容。然后,您可以这样做:
add(E element)
如果医生只是一个字符串,则可以从GroupBy中删除.Id
答案 1 :(得分:2)
我尝试了下面的代码,并且工作正常,您可以使用此代码:
//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
}
希望对您有帮助。
谢谢