这可以重构为一个LINQ语句吗?我觉得它可以但却无法绕过它。扩展方法和LINQ的混乱对我来说看起来很难看。
(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 :(得分: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));
}
}
阿哈:
现在我们可以重构:
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));
}
}