2009-10-21 82 views
1

這可以重構爲一個LINQ語句嗎?我覺得它可以,但不能包裹我的頭。擴展方法和LINQ的混雜只是讓我看起來很醜。LINQ to SQL重構foreach幫助

(db是一個DataContext。)

void AddToSeries(Series series, DateTime date) 
{ 
    foreach (var date in db.Ad.Select(ad => ad.DateTime.Date).Distinct()) 
    { 
     var phraseCount = (from pc in db.PhraseCount 
          where pc.DateTime.Date == date 
          select pc.Count).SingleOrDefault(); 

     var adCount = db.Ad.Where(ad => ad.DateTime.Date == date).Count(); 

     series.Add(new KeyValuePair<DateTime, double>(date, adCount)); 
    } 
} 
+0

phraseCount要求什麼? – 2009-10-21 12:18:40

回答

5

首先重構一貫的風格。

void AddToSeries(Series series, DateTime date) 
{ 
    var dates = db.Ad 
     .Select(ad => ad.DateTime.Date) 
     .Distinct(); 

    foreach (DateTime date in dates) 
    { 
     var phraseCount = db.PhraseCount 
      .Where(pc => pc.DateTime.Date == date) 
      .Select(pc => pc.Count) 
      .SingleOrDefault(); 

     var adCount = db.Ad 
      .Where(ad => ad.DateTime.Date == date) 
      .Count(); 

     series.Add(new KeyValuePair<DateTime, double>(date, adCount)); 
    } 
} 

阿哈:

  • phraseCount不使用
  • 鍵是日期,值是一個計數
  • 多個數據庫旅行是沒有樂趣
  • 這種方法
  • 日期參數被阻止由foreach變量

現在我們可以refa ctor:

void AddToSeries(Series series, DateTime date) 
{ 
    var pairs = db.Ad 
     .GroupBy(ad => ad.DateTime.Date) 
     .Select(g => new {key = g.Key, theCount = g.Count()}); 

    foreach (var x in pairs) 
    { 
     series.Add(new KeyValuePair<DateTime, double>(x.key, x.theCount)); 
    } 
}