使用LINQ的函数中引发异常

本文关键字:异常 函数 LINQ 使用 | 更新日期: 2023-09-27 18:20:48

我有一个简单的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;
        }

注释行是返回PatientId由Random类选择的患者的第一次尝试。它没有编译,我收到了错误Cannot implicitly convert type... (are you missing a cast)?然后我运行了没有被注释掉的迭代,得到了异常CCD_ 2。

所以我试着把它作为我的退货声明

 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);

使用LINQ的函数中引发异常

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

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

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

你也可以用更简单(更快)的代替你的整个功能

return patients.ElementAt(rand.Next(patients.Count()));

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

    //return from g in patList
    //       where g.PatientId == patientValue
    //       select g;