我有与性能的简单Patient类像异常使用LINQ
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
。
于是我想这是我的return语句
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);
可以将随机实例作为参数传递给方法,也可以在类中使用静态字段。否则,如果您在循环中调用“GetRandomPatient”,它将不会生成随机值,因为它的播种时间与播种时间一致。 –
@TimSchmelter:并注意'Random'不是线程安全的。 – SLaks
@SLaks你可以扩大这些影响? – wootscootinboogie