使用linq与列表进行比较

时间:2014-02-13 10:16:33

标签: c# 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);
}

有没有办法在不使用Linq

的情况下使用foreach

2 个答案:

答案 0 :(得分:3)

使用Enumberable.Intersect获取常用记录。

var commonClients = cids.Intersect<int>(_service.Patients.Select(x => x.ClientID));

var person = _service.Patients.Where(x => commonClients.Contains(x.ClientID));

答案 1 :(得分:3)

您可以在列表中使用Contains(顺便说一下,您不需要ToList:这样可以避免对数据库进行2次查询。)

var allPp = _service.Patients.Where(p1 => cids.Contains(p1.ClientId))
                             .Select(m >= new PatientDTO) {
                                   PatientID = m.PatientID,
                                PatientName = m.PatientName
                             });

但在db世界中,性能最佳的方式是加入

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,
}