LINQ to SQL重构foreach帮助

时间:2009-10-21 12:07:31

标签: linq-to-sql refactoring

这可以重构为一个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));
    }
}

1 个答案:

答案 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));
    }
}

阿哈:

  • 不使用phraseCount
  • 键是日期,值是计数
  • 多次数据库旅行并不好玩
  • 此方法的日期参数被foreach变量
  • 阻止

现在我们可以重构:

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));
    }
}