簡體   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