c# - 如何加快此 LINQ 查询的速度?

标签 c# asp.net performance linq entity-framework

我知道有一种更有效的方法可以做到这一点,使用谓词,但是相当新,我不确定如何去做。

List<HousingAssignment> list;

using (OEContext context = new OEContext())
{
    var query =
        from ha in context.HousingAssignments
        where ((ha.BedID == bed.ID) &&
                (((ha.CheckIn <= checkin) && (ha.CheckOut >= checkin)) ||
                ((ha.CheckIn <= checkout) && (ha.CheckOut >= checkout))))
        select ha;

    list = query.ToList();
}

return list.Count;

最佳答案

由于您只是返回计数,您可以在查询中使用 Count 计算它方法:

using (OEContext context = new OEContext())
{
  var query =
    from ha in context.HousingAssignments
    where ((ha.BedID == bed.ID) &&
            (((ha.CheckIn <= checkin) && (ha.CheckOut >= checkin)) ||
            ((ha.CheckIn <= checkout) && (ha.CheckOut >= checkout))))
    select ha;

  return query.Count();  
}

这消除了从本地数据库中提取值,存储到列表中,然后“丢弃”结果。相反,计数将在服务器上计算,您只会拉出一个数字。

您还可以通过对 CheckIn 的正确索引来潜在地加速服务器上的查询。和 CheckOut列。

关于c# - 如何加快此 LINQ 查询的速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17030796/

相关文章:

c# - 保存 PrintDialog 配置以供下次打开

c# - 如何在 LINQ 中获取所需的集合

c# - 具有未指定长度数组的 PInvoke 结构

c# - 使用 OAuth 2 的 Google 阅读器 API 错误 401

asp.net - Azure 构建管道 : dotnet build fails with: FileNotFoundException: Could not load file or assembly 'TechTalk. SpecFlow,版本 = 3.1.0.0

asp.net - 调整图像大小和性能

asp.net - 如何使用 Web 控件的 Jquery 将文本分配给标签

C# 如何压缩.ashx 内容?

java - 遍历一个巨大的列表,检查字符串是否等于 true

ruby-on-rails - 对象实例的未定义​​方法 `includes'