views:

62

answers:

1

Can this be refactored into one LINQ statement? I feel like it can be but can't wrap my head around it. The mishmash of extension methods and LINQ just looks ugly to me.

(db is a 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));
    }
}
+5  A: 

First refactor to consistent style.

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

Aha:

  • phraseCount is not used
  • key is a date, value is a count
  • multiple database trips is no fun
  • date parameter for this method is blocked by the foreach variable

Now we can refactor:

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