2010-01-22 60 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的任何方法。