繁体   English   中英

LINQ? 重构foreach

[英]LINQ? Refactoring foreach

有没有更好的方法来写这个? 我觉得最近做完很多JavaScript之后,我对C#感到生疏。 这可以改善吗?

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

好的,您可以使用LINQ查询语法(带有fromwhere 编写它,但是我不确定这是一个很大的改变。 我会更想知道是否不需要查找:

this.CartItems[this.CartItems.IndexOf(item)].EffectivePrice = 
            CurrencyHelper.GetLocalizedCurrency(item.EffectivePrice);

至:

item.EffectivePrice = CurrencyHelper.GetLocalizedCurrency(item.EffectivePrice);

除此之外,我不确定是否值得进行更改。 我可能将其保留为:

foreach (var item in this.CartItems) {
    if (item.EffectivePrice != null) {
        item.EffectivePrice = CurrencyHelper.GetLocalizedCurrency(item.EffectivePrice);
    }
}

直接回答您的问题(有关如何在Linq中实现代码):

this.CartItems.Where(item => item.EffectivePrice != null).ToList().ForEach
(
   item =>
      item.EffectivePrice = CurrencyHelper.GetLocalizedCurrency(item.EffectivePrice);
);

没有理由必须在列表中明确指定项目的索引(至少我没有看到原因)。 .ToList()为您提供对象引用的List <T>,供您管理。 您使用AsQueryable()可以节省一些CPU周期。

但是,用方法调用的结果覆盖属性有点奇怪,因为对该属性的后续方法调用可能会一遍又一遍地更改值。

但是,尽管如此,Linq的方法要优雅得多。 我可以看到,缺点是无法使用包含Linq的任何方法进行编辑和继续。

我认为您可以执行以下操作:

foreach (var item in this.CartItems.Where(i => i.EffectivePrice != null)) 
{ 
        item.EffectivePrice =  
            CurrencyHelper.GetLocalizedCurrency(item.EffectivePrice); 
}

除了Marc的观点外,LINQ更适用于功能性的东西,并且对变异现有数据结构没有太大帮助。 这是一件好事。 因此,如果您想产生一个对象数组,则可以使用以下方法:

var newItems = CartItems
    .Select(i => CreateNewItemWithPrice(i, item.EffectivePrice ?? 
        CurrencyHelper.GetLocalizedCurrency(item.EffectivePrice))
    .ToList();

通常,这是一个非常好的方法,因为对数据进行变异会导致很多错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM