如何提高我的linq查询的性能

本文关键字:性能 查询 linq 何提高 我的 | 更新日期: 2023-09-27 18:03:43

我使用Linq编写了以下代码。

 return (from item in this
          where item.IsMatch(orgid, postcode, shipmentMethod, providerCode)
          orderby item.OrderID
          select item.DTime).FirstOrDefault();

对于200万条记录,需要超过10分钟才能返回一个值。有人能帮助我如何将此查询转换为使用ParallelEnumerable的查询吗?

任何其他的建议如何优化性能是欢迎的。

***上面的示例引用了从IEnumerable继承的自定义类。IsMatch()方法内部有一些条件:

public bool IsMatch(long orgid, string postcode, string shipmentMethod, string providerCode)
{
    if (string.IsNullOrWhiteSpace(providerCode)) providerCode = null;
    if (string.IsNullOrWhiteSpace(shipmentMethod) || shipmentMethod == "0") shipmentMethod = null;
    return (OrgID == 0 || orgid == OrgID) &&
            PostcodeFrom.Length == postcode.Length &&
            string.CompareOrdinal(PostcodeFrom, postcode) <= 0 &&
            string.CompareOrdinal(PostcodeTo, postcode) >= 0 &&
            (ShipmentMethod == null || shipmentMethod == ShipmentMethod) &&                    (ProviderCode == null || providerCode == ProviderCode);
}

如何提高我的linq查询的性能

Try

return this.AsParallel()
    .Where(p=> p.IsMatch(orgid, postcode, shipmentMethod, providerCode))
    .Min(p=> p.OrderID)
    .Select(p=> p.DTime);

dymanoid所述,OrderBy不需要。

TPL应该能够利用Where()Min()的并行性