0

我有一个简单的 Patient 类,其属性如下

 public int PatientId { get; set; }
 public string FirstName { get; set; }
 public string LastName { get; set; }

以及一个根据 PatientId 返回随机患者的函数,例如

 public static Patient GetRandomPatient(IEnumerable<Patient> patList)
        {
            Random r = new Random();
            int patientValue = r.Next(patList.Min().PatientId, patList.Max().PatientId);
            //return from g in patList
            //       where g.PatientId == patientValue
            //       select g;
            var test = from g in patList
                       where g.PatientId == patientValue
                       select g;
            return (Patient)test;
        }

注释掉的行是返回由 Random 类选择的 PatientId 的患者的第一次尝试。那没有编译,我得到了错误 Cannot implicitly convert type... (are you missing a cast)? 所以然后我运行了没有被注释掉的迭代并得到了异常 At least one object must implement IComparable

所以然后我尝试了这个作为我的回报声明

 Patient testPatient = patList.First(x => x.PatientId == patientValue);
 return testPatient;

这编译没有错误,但是当我运行它时,我得到一个对象必须实现 IComparable 的相同异常。

我想知道两件事 1. 关于使用 LINQ 语法从列表中返回单个对象,我似乎不太了解的概念(在这种情况下,每个 PatientId 都是唯一的,因此 return 语句可以只能返回一个 Patient 对象)?2. 为什么代码

Patient testPatient = patList.First(x => x.PatientId == patientValue);
 return testPatient;

编译并且没有给出编译器错误,但是其他迭代具有相同的异常的炸弹?

主功能

         List<Patient> patientList = new List<Patient>();
    patientList.Add(new Patient() { PatientId = 101, FirstName = "John", LastName = "Jacosdfasdfasdfb" });
                    patientList.Add(new Patient() { PatientId = 100, FirstName = "Mary", LastName = "Wilson" });
                    patientList.Add(new Patient() { PatientId=102, FirstName="Max",LastName="Payne"}); 
//Call that bombs the program Console.WriteLine(Patient.GetRandomPatient(patientList).PatientId);
4

2 回答 2

7

正如错误试图告诉你的那样,你的.Min().Max()调用没有意义。
您只能调用Min()或调用Max()可以相互比较的对象集合。

相反,您需要在一组 ID 上调用它们:

patients.Select(p => p.PatientId).Min()

您还可以用更简单(更快)的方式替换整个函数

return patients.ElementAt(rand.Next(patients.Count()));
于 2013-07-03T14:30:53.127 回答
0

当谈到第一条语句时,我对错误消息的其余部分感到好奇,哪些类型不能被隐式转换,我敢打赌 PatientId 是字符串或可为空的 int(int?),而您正在与普通整数进行比较。

    //return from g in patList
    //       where g.PatientId == patientValue
    //       select g;
于 2013-07-03T14:34:20.913 回答