2009-10-21 207 views
1

您將如何重構此代碼,相對於LINQ?我是LINQ的新手,並沒有很好地處理更復雜的查詢(嵌套,分組)。需要LINQ重構幫助

所有這三個語句和foreach循環都可以轉換爲一個LINQ語句嗎?

void AddSeries(Series series, int phraseId) 
{ 
    using (var db = Database.Instance) 
    { 
     foreach (var date in db.Ad.Select(ad => ad.DateTime.Date).Distinct()) 
     { 
      var phraseCount = (from pc in db.PhraseCount 
           where pc.DateTime.Date == date && 
            pc.PhraseId == phraseId 
           select pc.Count).SingleOrDefault(); 

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

      series.Add(date, phraseCount/adCount); 
     } 
    } 
} 

回答

1

這是我的第一槍。很難,沒有你的模型。

var q = from ad in db.Ad 
     group ad by ad.DateTime.Date into g 
     select new 
     { 
      AdCount = g.Count(), 
      Date = g.Key, 
      PhraseCount = (from pc in db.PhraseCount 
          where pc.DateTime.Date == g.Key 
           && pc.PhraseId == phraseId 
          select pc).Count() 
     } 
+1

可能需要將Date = g.Key添加到select中。 – dahlbyk

+0

是的,謝謝dahlbyk –