Wesley Bakker

Interesting things I encounter doing my job...

Sponsors

News

Wesley Bakker
motion10
Rivium Quadrant 151
2909 LC Capelle aan den IJssel
Region of Rotterdam
The Netherlands
Phone: +31 10 2351035

(feel free to chat with me)
 

Add to Technorati Favorites

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.

Posted: Aug 21 2008, 10:58 AM by webbes | with 2 comment(s)
Filed under:

Comments

David A Kearns said:

Can't remember something I don't think I've ever seen before...

Not sure if I've ever had the challenge that would lend itself to this either...

# August 21, 2008 4:52 PM

Dew Drop - August 22, 2008 | Alvin Ashcraft's Morning Dew said:

Pingback from  Dew Drop - August 22, 2008 | Alvin Ashcraft's Morning Dew

# August 22, 2008 9:30 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)