LINQ to Objects,如何更新List中的项目?

Dav*_*veK 3 c# linq

我目前有以下工作代码.然而,这是非常缓慢的.我知道将所有权作为查询而不是列表传递可能会简化并加快速度,但由于各种原因,这是不可能的.

如何在不创建新列表的情况下更新现有的馆藏列表?其他改进代码的建议?

internal List<DailyHoldingItem> TransformHoldingItemsToCurrency(List<DailyHoldingItem> holdings,string toCurrency)
        {
        //TODO - how to do this calculation in place, without creating a new list?
        var query = (from holding in holdings
                     from fxRateHolding in amdw.FXRates
                     from fxRateToCur in amdw.FXRates
                     where
                     fxRateHolding.BaseCurrency == holding.Currency &&
                     fxRateToCur.BaseCurrency == toCurrency &&
                     fxRateHolding.ValueDate == holding.Date &&
                     fxRateToCur.ValueDate == holding.Date
                     select new { holding, fxRateHolding, fxRateToCur });

        return query.Select(dhi =>
        {
            decimal factor = dhi.fxRateToCur.Value / dhi.fxRateHolding.Value;
            dhi.holding.MarketValue *= factor;
            dhi.holding.Fee *= factor;
            dhi.holding.Remuneration *= factor;
            return dhi.holding;
        }).ToList();

    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

好吧,有一件事你可以使用连接来加快速度,并且只评估一次有效的"目标"货币:

var targetRates = amdw.FXRates
                      .Where(rate => rate.BaseCurrency == toCurrency)
                      .ToList();

var query = from holding in holdings
            join fxRateHolding in amdw.FXRates
              on new { holding.Currency, holding.Date } equals
                 new { Currency = fxRateHolding.BaseCurrency, 
                       Date = fxRateHolding.ValueDate }
            join fxRateToCur in targetRates
              on holding.Date equals fxRateToCur.ValueDate
            select new { holding, fxRateHolding, fxRateToCur };
Run Code Online (Sandbox Code Playgroud)

我个人不会尝试更新列表,我不会改变现有的馆藏(正如你目前在Select通话中所做的那样).改变现有值往往会使您的代码难以推理 - 这就是为什么LINQ 旨在以更多功能的方式使用.