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

时间:2015-07-21 14:11:37

标签: c# .net performance linq

我使用Linq使用以下代码。

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

对于2百万条记录,返回值需要10分钟以上。 有人可以帮助我如何使用ParallelEnumerable将此查询转换为一个查询?

欢迎任何其他建议如何优化perfrormance ..

***以上示例引用了继承自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);
}

1 个答案:

答案 0 :(得分:0)

尝试

 -(void)saveResults:(NSArray *)results forKey:(NSString *)key
    {
        NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithDictionary:[self getResultsDict]];
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:results];
        if(dict == nil){
            dict = [NSMutableDictionary dictionaryWithObject:data forKey:key];
        }else{
            [dict setObject:data forKey:key];
        }

        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:dict forKey:@"RESULTS_DICT"];
        [userDefaults synchronize];
    }

    -(NSArray*)readFullResults:(NSString *)key
    {
        NSDictionary *dict = [self getResultsDict];
        NSArray *result = nil;
        if(dict != nil){
            [dict objectForKey:key];
            NSData *data = [dict objectForKey:key];;
            result = [NSKeyedUnarchiver unarchiveObjectWithData: data];
        }
        return result;
    }

    -(NSArray*) getDates
    {
        NSDictionary *dict = [self getResultsDict];
        if(dict != nil)
        {
            return [dict allKeys];
        }
        return nil;
    }

    - (NSDictionary*)getResultsDict{
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSMutableDictionary *resultsDict = [userDefaults objectForKey:@"RESULTS_DICT"];
        return resultsDict;

    }

dymanoid 所述,return this.AsParallel() .Where(p=> p.IsMatch(orgid, postcode, shipmentMethod, providerCode)) .Min(p=> p.OrderID) .Select(p=> p.DTime); 是不必要的。

TPL应该能够在OrderByWhere()

中使用并行性