避免循环生成可为空的集合,提高性能

图罗

我一直在使用秒表,但就性能而言,以下查询看起来非常昂贵,即使我已经在以下内容中找到了基于各种读数的最佳选择(用for更改foreach循环,使用数组而不是集合,使用匿名类型而不是从数据库获取整个表)。有没有办法使它更快?我需要填写价格数组,该数组必须为空。我不确定是否要丢失一些东西吗?

public float?[] getPricesOfGivenProducts(string[] lookupProducts)
{
    var idsAndPrices = from r in myReadings select 
                       new { ProductId = r.ProductId, Price = r.Price };

    float?[] prices = new float?[lookupProducts.Length];
    for(int i=0;i<lookupProducts.Length;i++)
    {
        string id = lookupProducts[i];
        if (idsAndPrices.Any(r => r.ProductId == id))
        {
            prices[i] = idsAndPrices.Where(p => p.ProductId == id)
            .Select(a=>a.Price).FirstOrDefault();
        }
        else
        {
            prices[i] = null;
        }
    }
    return prices;
}
克里斯·曼特尔

假设idsAndPricesIEnumerable<T>,您应该对其进行初始化:

var idsAndPrices = (from r in myReadings select 
                   new { ProductId = r.ProductId, Price = r.Price })
                   .ToList();

可能会致电给:

idsAndPrices.Any(r => r.ProductId == id)

和:

idsAndPrices.Where(p => p.ProductId == id)

..导致IEnumerable<T>每次调用时都要对其进行评估。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章