[英]Compare with list using linq
我有一個這樣獲取的清單cids
var cids = _service.Employee.Where(i => i.EmpID == _empID).Select(j => j.ClientID).ToList();
我想將此列表與Patient Entity
進行比較,並獲取與cid list
中的clientId匹配的患者的所有記錄
患者實體就是這樣
class Patient
{
Int PatientID{ get; set;}
Int ClientID{get; set;}
string PatientName{get; set;}
}
現在我正在這樣做
foreach(var item in cids)
{
var pp = from p1 in _service.Patients
where p1.ClientId == item
select new PatientDTO
{
PatientID = p1.PatientID,
PatientName = p1.PatientName,
};
prec.Add(pp);
}
有沒有辦法在不使用foreach
情況下使用Linq
使用Enumberable.Intersect獲取常見記錄。
var commonClients = cids.Intersect<int>(_service.Patients.Select(x => x.ClientID));
var person = _service.Patients.Where(x => commonClients.Contains(x.ClientID));
您可以在列表中使用Contains
(順便說一下,您不需要ToList
:這樣可以避免對db進行2次查詢)。
var allPp = _service.Patients.Where(p1 => cids.Contains(p1.ClientId))
.Select(m >= new PatientDTO) {
PatientID = m.PatientID,
PatientName = m.PatientName
});
但是,在數據庫世界中,最高效的方式是聯接
from emp in _service.Employee.Where(i => i.EmpID == _empID)
join patient in _service.Patients on emp.ClientId equals patient.ClientId
select new PatientDTO {
PatientID = patient.PatientID,
PatientName = patient.PatientName,
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.