Remember Yield?

The Yield Statement

A lot of the times when developers need some sort of enumeration they tend to create a generic list by default. Even if they realy need to iterate that list only once. Some good examples can be found in solutions offered to this code puzzle at less than dot(which is a great newcomer).

Yield

Instead of creating a list first you can use the yield statement just as well. So here's how I would solve this puzzle:

static void Main() {
    Stopwatch sw = new Stopwatch();
    sw.Start();

    DateTime startDate = DateTime.Now;
    DateTime endDate = startDate.AddYears(10);

    DayOfWeek dayOfWeek = DayOfWeek.Friday;
    int day = 13;

    foreach (DateTime date in DayOfWeekAtMonthDay(startDate, endDate, dayOfWeek, day)) {
        Console.WriteLine(date.ToLongDateString());
    }

    sw.Stop();
    Console.WriteLine(sw.ElapsedMilliseconds);

    Console.ReadLine();
}

private static IEnumerable DayOfWeekAtMonthDay(DateTime startDate, DateTime endDate, DayOfWeek dayOfWeek, int day) {
    DateTime checkDate = startDate;

    int dayDiff = day - checkDate.Day;
    if (dayDiff < 0) {
        checkDate = checkDate.AddMonths(1);
    }

    checkDate = checkDate.AddDays(dayDiff);

    while (checkDate <= endDate) {
        if (checkDate.DayOfWeek == dayOfWeek) {
            yield return checkDate;
        }
        checkDate = checkDate.AddMonths(1);
    }
}

Cheers,

Wes

P.S. Do not use this code because it is really buggy.. it's just to point out the use of yield instead of generic lists.

1 Comment

Comments have been disabled for this content.