优化LINQ查询

时间:2013-12-11 16:21:58

标签: c# sql linq

我想优化我的LINQ查询。

Orders = (from m in dataContext.SupplierOrdersViews
          where (fromDate != toDate ?
                 m.RecordCreated >= fromDate && m.RecordCreated <= toDate :
                 (m.RecordCreated.Value.Year == fromDate.Year &&
                  m.RecordCreated.Value.Month == fromDate.Month &&
                  m.RecordCreated.Value.Day == fromDate.Day))
          select new
          {
             id = m.ID,
             RecordCreated = m.RecordCreated,
             RecordDeleted = m.RecordDeleted,
             Status = m.Status,
             DepRunningNo = m.DepRunningNo,
             Name = m.Name,
             Address1 = m.Address1,
             VehicleRegNo = m.VehicleRegNo,
             ProductName = m.ProductName,
             Tare = m.Tare < m.Gross ? m.Tare : m.Gross,
             Gross = m.Tare < m.Gross ? m.Gross : m.Tare,
             NetWeight = m.NetWeight,
             NetPrice = m.NetPrice
          }).OrderBy(m => m.RecordCreated).ThenByDescending(m => m.Status != 2).ToList();

我认为问题在于这些问题:

Tare = m.Tare < m.Gross ? m.Tare : m.Gross,

Gross = m.Tare < m.Gross ? m.Gross : m.Tare,

这是如何在幕后工作的,有没有更好的方法来完成它?我很高兴它有效,但它并不完美。这将使用(使用默认过滤器)77个记录填充网格,这需要3秒......太长了!

是否有更好的方法来分配毛/稗?我需要进行类似于此处的检查,因为权重模糊地存储在数据库中。

1 个答案:

答案 0 :(得分:5)

fromDatetoDate每行不变;它们是针对整个查询修复的,因此您可以在查询之前执行此操作,而不是将该检查作为查询的一部分:

Expression<Func<SupplierOrders, bool>> filter;

if(fromDate != toDate)
    filter = m => m.RecordCreated >= fromDate && m.RecordCreated <= toDate;
else
    filter = m => (m.RecordCreated.Value.Year == fromDate.Year &&
                  m.RecordCreated.Value.Month == fromDate.Month &&
                  m.RecordCreated.Value.Day == fromDate.Day);

dataContext.SupplierOrdersViews.Where(filter)
    //the rest of the query goes here