## Finding a Time of Interest in a Dictionary

Given a dictionary list whose keys are a list of dates, how would you find the item that has a date <= a specific time of interest.

For example: Given the following dates in the dictionary and a Time of Interest = 11am, the result should be 6am.

• 6am on 1/2/2009
• 12am on 1/2/2009
• 6pm on 1/2/2009

Here’s a little test I threw together to test this out. Can you improve on it?

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// forecasts by date (populated earlier)
DateTime mTimeResult;
Dictionary dForecast = new Dictionary();

dForecast.Add(new DateTime(2009, 2, 4, 6, 0, 0), “6 am”);
dForecast.Add(new DateTime(2009, 2, 4, 12, 0, 0), “12 Noon”);
dForecast.Add(new DateTime(2009, 2, 4, 18, 0, 0), “6 pm”);

// Test 1 – Time of Interest is less than the dates in the dictionary
mTimeResult = FindInterest(dForecast, new DateTime(2008, 1, 4, 15, 0, 0));
System.Diagnostics.Debug.Assert(mTimeResult == DateTime.MinValue, “BAD Test 1”);

// Test 2 – Time of Interest is set to the dates in the dictionary and set to 5am.
mTimeResult = FindInterest(dForecast, new DateTime(2009, 2, 4, 5, 0, 0));
System.Diagnostics.Debug.Assert(mTimeResult == DateTime.MinValue, “BAD Test 2”);

// Test 3 – Time of Interest is in the dictionary and set to 6am.
mTimeResult = FindInterest(dForecast, new DateTime(2009, 2, 4, 6, 0, 0));
System.Diagnostics.Debug.Assert(mTimeResult == new DateTime(2009, 2, 4, 6, 0, 0), “BAD Test 3”);

// Test 4 – Time of Interest is in the dictionary and set to 11am.
mTimeResult = FindInterest(dForecast, new DateTime(2009, 2, 4, 11, 0, 0));
System.Diagnostics.Debug.Assert(mTimeResult == new DateTime(2009, 2, 4, 6, 0, 0), “BAD Test 4”);

// Test 5 – Time of Interest is in the dictionary and set to 1pm.
mTimeResult = FindInterest(dForecast, new DateTime(2009, 2, 4, 13, 0, 0));
System.Diagnostics.Debug.Assert(mTimeResult == new DateTime(2009, 2, 4, 12, 0, 0), “BAD Test 5”);

// Test 6 – Time of Interest is in the dictionary and set to 7pm.
mTimeResult = FindInterest(dForecast, new DateTime(2009, 2, 4, 19, 0, 0));
System.Diagnostics.Debug.Assert(mTimeResult == DateTime.MinValue, “BAD Test 6”);

// Test 7 – Time of Interest is in the dictionary and set to DateTime.MaxValue.
mTimeResult = FindInterest(dForecast, DateTime.MaxValue);
System.Diagnostics.Debug.Assert(mTimeResult == DateTime.MinValue, “BAD Test 7”);

}

public static DateTime FindInterest(Dictionary dForecast, DateTime mTimeInterest)
{
// Find the key that corresponds to our needs or return DateTime.MinValue;
return dForecast.Where(x => x.Key <= mTimeInterest).LastOrDefault().Key; } } } [/sourcecode] So did you notice the bug? What if the dictionary list is not sorted? What happens then? 🙂 You should sort the dictionary before the WHERE clause.

Tagged , , , ,