c# – LINQ:如何使用IQueryable()选择特定列

我只需从Hospital表,HospitalId和Name中选择两列.

我尝试下面的代码,它选择医院表中的所有列,导致性能下降.请帮我从医院表中选择两列

public HttpResponseMessage GetAvailableHospitalsByAjax(System.Guid? DirectorateOfHealthID = null, System.Guid? UnitTypeID = null, string DeviceTypeIDs = null)
{
    Context db = new Context();
    var query = db.Hospitals.AsQueryable();
    if (UnitTypeID != null)
    {
        query = query.Where(j => j.HospitalDepartments.Any(www => www.Units.Any(u => u.UnitTypeID == UnitTypeID)));
    }

    if (DirectorateOfHealthID != null)
    {
        query = query.Where(h => h.DirectorateHealthID == DirectorateOfHealthID);
    }


    query = query.Where(j => j.HospitalDepartments.Any(u => u.Units.Any(d => d.Devices.Any(s => s.Status == Enums.DeviceStatus.Free)))
    && j.HospitalDepartments.Any(hd => hd.Units.Any(u => u.Beds.Any(b => b.Status == Enums.BedStatus.Free))));



    var list = query.ToList().Select(w => new HospitalInfo()
    {
        Id = w.ID,
        Name = w.Name 

    }).ToList();


    return Request.CreateResponse(HttpStatusCode.OK, list);
}

最佳答案 在投影之前删除ToList调用:

  var list = query.Select(w => new HospitalInfo()
  {
     Id = w.ID,
     Name = w.Name 

  }).ToList();

通过该ToList调用,您可以在进行投影之前实现查询

点赞