如何优化此LinQ查询?

时间:2016-06-20 12:23:34

标签: c# linq

model.mTable = m_ctx.Shop
 .Where(t => t.CustomerID== model.mFilter.CustomerID)
 .Select(f => new GroupedData
  {
      iGroupID = f.iCustomerID,
      dtGroupDt = new DateTime(f.dtDate.Year, f.dtDate.Month, f.dtDate.Day, f.dtStartTime.Hours, f.dtStartTime.Minutes, f.dtStartTime.Seconds, f.dtStartTime.Milliseconds),
 })
 .OrderByDescending(f => f.dtGroupDt)
 .Take(2)
 .ToList();

Shop是表,CustomerID是表的主键,但是如果有大量数据,则此查询会给出超时异常。有没有办法优化这个查询?

1 个答案:

答案 0 :(得分:1)

有三件事可以帮助你:

1)如果可能,将dtDatedtStartTime合并为一列 2)在dtDate上创建索引(参见@TimothyStepansky评论)然后再生 3)重新排序执行查询的方式(未经测试,语法可能不完全正确):

model.mTable = m_ctx.Shop
              .Where(t => t.CustomerID== model.mFilter.CustomerID)
              .OrderByDescending(t => t.dtDate)
              .ThenBy(t => t.dtStartTime)
              .Select(f => new GroupedData
              {
                  iGroupID = f.iCustomerID,
                  dtGroupDt = new DateTime(f.dtDate.Year, f.dtDate.Month, f.dtDate.Day, f.dtStartTime.Hours, f.dtStartTime.Minutes, f.dtStartTime.Seconds, f.dtStartTime.Milliseconds),
              })
              .Take(2)
              .ToList();