2010-01-22 63 views
2

有没有更好的方式来写这个?最近我做了很多JavaScript之后,我觉得自己正在用C#生锈。这可以改善吗?LINQ?重构foreach

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

回答

5

好了,你可以它与fromwhere LINQ查询语法,但我不知道它是一个改变;我更想知道,如果查找是不必要的:

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

到:

​​

除此之外,我不知道这是值得去改变它;我可能会离开它,因为:

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

+1,我不确定这个问题是否非常适合LINQ。 – Sapph 2010-01-22 05:11:52

0

我认为你可以做这样的事情:

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

除了马克的角度来看,LINQ是更多的功能(ISH)的东西,而不是在现有的突变数据结构,从而帮助。这是一件好事。所以,如果你想制作一个阵列的对象,你会喜欢的东西去:

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

在一般情况下,这是一个非常好的方法,因为变异的数据可能会导致一个可怕的很多错误。

2

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

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

没有理由必须明确指定列表中的项目的索引(至少我的天堂没有看到一个理由)。 .ToList()为您提供了一个供您管理的对象引用的列表<T>。你AsQueryable()来节省几个CPU周期。

然而,使用方法调用的结果覆盖一个属性有点奇怪,因为后续对该属性的方法调用可能会一次又一次地改变该值。

但是,Linq的方法更加优雅。我可以看到的缺点是无法编辑和继续使用包含Linq的任何方法。