gpt4 book ai didi

c# - LINQ to Objects,如何就地更新列表中的项目?

转载 作者:行者123 更新时间:2023-11-30 14:01:20 25 4
gpt4 key购买 nike

我目前有以下工作代码。然而,它的速度非常慢。我知道将馆藏作为查询而不是列表传递可能会简化和加快处理速度,但由于各种原因这是不可能的。

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

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();

}

最佳答案

一方面,您可以使用连接加快速度,并且只评估一次有效的“目标”货币:

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 };

就我个人而言,我不会尝试更新列表并且我不会改变现有的馆藏(正如您目前在Select调用)。改变现有值往往会使您的代码更难推理 - 这就是 LINQ 设计以更实用的方式使用的原因。

关于c# - LINQ to Objects,如何就地更新列表中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8501566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com