LINQ?重构foreach

Jam*_*ead 2 c# linq

有没有更好的方法来写这个?在最近做了很多JavaScript之后,我觉得我已经厌倦了C#.这可以改善吗?

    foreach (var item in this.CartItems)
    {
        if (item.EffectivePrice != null)
        {
            this.CartItems[this.CartItems.IndexOf(item)].EffectivePrice = 
                CurrencyHelper.GetLocalizedCurrency(item.EffectivePrice);
        }
    }
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 5

好吧,你可以使用a from和a 在LINQ查询语法中编写它where,但我不确定它是一个很大的变化; 我更想知道查找是否是不必要的:

this.CartItems[this.CartItems.IndexOf(item)].EffectivePrice = 
            CurrencyHelper.GetLocalizedCurrency(item.EffectivePrice);
Run Code Online (Sandbox Code Playgroud)

至:

item.EffectivePrice = CurrencyHelper.GetLocalizedCurrency(item.EffectivePrice);
Run Code Online (Sandbox Code Playgroud)

除此之外,我不确定是否值得花钱改变它; 我可能会把它留作:

foreach (var item in this.CartItems) {
    if (item.EffectivePrice != null) {
        item.EffectivePrice = CurrencyHelper.GetLocalizedCurrency(item.EffectivePrice);
    }
}
Run Code Online (Sandbox Code Playgroud)