foreach裡有條件之改寫

2014年10月1日 星期三

利用lambda改寫可讓原來的程式更為精簡,請看以下的範例 原來寫法

var result = CacheService.Current.GetAllMarketType();
var entities = new List();
if (result != null)
{
 // Make up model data from service return.
 foreach (MarketType marketType in result)
 {
  if (marketType.Status != MarketTypeStatus.DELETED)
  {
   entities.Add(
    new MarketTypeEntity(marketType)
    {
     Id = marketType.id,
     From = marketType.From,
     To = marketType.To,
     Interval = marketType.Interval,
     MaximumRange = marketType.maximumRange,
     MinimumRange = marketType.minimumRange,
     Status = marketType.Status
    });
  }
 }
}

用lambda可改為

var result = CacheService.Current.GetAllMarketType();
var entities = new List();
if (result != null)
{
  entities.AddRange(
  result.Where(o => o.Status != MarketTypeStatus.DELETED)
  .Select(marketType => new MarketTypeEntity(marketType)
  {
   Id = marketType.MarketTypeId,
   From = marketType.From,
   To = marketType.To,
   Interval = marketType.Interval,
   MaximumRange = marketType.maximumRange,
   MinimumRange = marketType.minimumRange,
   Status = marketType.Status
  })
 );
}

0 意見: