简体   繁体   English

使用LINQ在函数中引发异常

[英]Exception thrown in function using LINQ

I've got a simple Patient class with properties like 我有一个简单的Patient类,其属性如下

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

and a function to return a random patient based on their PatientId like 以及根据其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;
        }

The commented out lines are the first attempt at returning the patient whose PatientId was chosen by the Random class. 带注释的行是返回由Random类选择其PatientId的患者的首次尝试。 That didn't compile and I was given the error Cannot implicitly convert type... (are you missing a cast)? 那没有编译,并且给出了错误Cannot implicitly convert type... (are you missing a cast)? So then I ran the iteration that isn't commented out and got the exception At least one object must implement IComparable . 因此,我运行了未注释掉的迭代,并得到了异常At least one object must implement IComparable

So then I tried this as my return statement 所以我尝试了这作为我的退货声明

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

This compiles without an error, but when I run it I get the same exception that one object must implement IComparable. 编译时没有错误,但是当我运行它时,我得到一个对象必须实现IComparable的异常。

I would like to know two things 1. What seems to be the concept that I'm not quite getting here with regard to returning a single object from a list using LINQ syntax (In this situation, each PatientId is unique so the return statement could only possible return a single Patient object)? 我想知道两件事:1.关于使用LINQ语法从列表中返回单个对象的概念,我似乎不太了解(在这种情况下,每个PatientId都是唯一的,因此return语句可以只能返回一个患者对象)? 2. Why does the code 2.为什么要编写代码

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

compile and give no compiler errors, but bombs with the same exception the other iterations have? 编译并且不给出编译器错误,但是炸弹具有与其他迭代相同的例外?

Main function 主功能

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

As the error is trying to tell you, your .Min() and .Max() calls don't make sense. 由于错误正试图告诉您,因此您的.Min().Max()调用没有任何意义。
You can only call Min() or Max() on a collection of objects that can be compared to each-other. 您只能在可以相互比较的对象集合上调用Min()Max()

Instead, you need to call them on a collection of IDs: 相反,您需要在一组ID上调用它们:

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

You can also replace your entire function with the simpler (and faster) 您还可以用更简单(更快)替换整个功能

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

When it comes to the first statement I am curious of the rest of the error message, what types cannot be implicitly converted, my bet is that PatientId is string or nullable int (int?) while you are compating with a normal integer. 当谈到第一条语句时,我对其余的错误消息感到好奇,无法隐式转换哪些类型,我敢打赌,当您使用普通整数进行编译时,PatientId是字符串或可为null的int(int?)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Linq:当object为null时,将引发异常 - Linq: When object is null an exception is thrown LINQ和Exception已被调用目标抛出 - LINQ and Exception has been thrown by the target of an invocation 由函数引发的异常,其中函数在引发异常时调用 - Exception thrown by a function, where that function called when exception thrown in it 在 .Net Core 2.1 中使用 FirstOrDefault 时抛出 System.Linq.Expressions 异常 - System.Linq.Expressions exception thrown when using FirstOrDefault in .Net Core 2.1 使用linq插入批量数据时发生错误{引发了&#39;System.OutOfMemoryException&#39;类型的异常。} - Error occured while inserting bulk data by using linq {Exception of type 'System.OutOfMemoryException' was thrown.} 使用反射,会引发安全异常 - Using Reflection, a security exception is thrown 尝试评估 LINQ 查询参数表达式时引发异常 - An exception was thrown while attempting to evaluate a LINQ query parameter expression InvalidOperationException:尝试评估 LINQ 查询参数表达式时引发异常 - InvalidOperationException: An exception was thrown while attempting to evaluate a LINQ query parameter expression EF LINQ查询if子句中抛出空引用异常 - Null reference exception being thrown in EF LINQ query if-clause Linq select-处理将引发超出范围异常的情况 - Linq select - handle situation where out of bounds exception would be thrown
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM