繁体   English   中英

如何提高linq查询的性能?

[英]How to improve performance of my linq query?

我有以下代码使用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);
}

尝试

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

正如dymanoid所提到的, OrderBy是不必要的。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM