Captain Comic
Captain Comic

Reputation: 16186

C# dictionary, need advice

I want to write some sort of dictionary that would accept current time and return what user-define time period it is. As time-preiod I mean user-defined names for time period that are read from file. For example

8:00-9:00 - breakfast time 9:00-12:00 - work time 12:00-13:00 - lunch time

etc...

Currently I have a function is base on if-else if statements

// C# syntax omitted for simplicity
TimePeriod GetCurrentTimePeriod(DateTime t)
{
 if(t < 8.00)
 {
  return TimePeriod.Sleep;
 }
 else if(t < 9.00)
 { 
   ...
 }
}

I am not happy with this straight solution. I would prefer use some sort of "dictionary" instead.

PS. Changed the word TimeZone to TimePeriod to avoid confusion with System.TimeZone class.

Upvotes: 0

Views: 282

Answers (4)

Eric Lippert
Eric Lippert

Reputation: 659956

This question was asked a couple of days ago. See the answer here for some ideas of how to proceed.

A dictionary object that uses ranges of values for keys

Upvotes: 3

sashaeve
sashaeve

Reputation: 9607

You have not to use TimeZone class because you will get different time in specific time zone.

You can use this class for time converting, e.g.

TimeZone localZone = TimeZone.CurrentTimeZone;
DateTime baseUTC = new DateTime(2010, 1, 1);
DateTime localTime = localZone.ToLocalTime(baseUTC);
TimeSpan localOffset = localZone.GetUtcOffset(localTime);

You may use simple check as answer to your question:

if (youTime >= 8.00 && youTime <= 9.00)
 return YourTypes.Breakfast; 
else if (youTime > 9.00 && youTime <= 12.00)
 return YourTypes.WorkTime;
else
 // etc.

Upvotes: 1

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421968

If you need to make those "periods of time" dynamically adjustable, I suggest building up a simple List of a record containing start time, end time, and description and simply query that list with LINQ. Since the number of items in that list is probably likely to be very small, linear search does the job and it isn't worth it to bother using binary search or more advanced data structures like segment trees:

class PeriodOfTime { 
   public DateTime StartTime {get; set;}
   public DateTime EndTime {get; set;}
   public string Description {get; set;} // Use your own enum instead
}
// ... 
List<PeriodOfTime> periods = new List<PeriodOfTime>();

var timeToQuery = DateTime.Now.TimeOfDay;
var period = periods.FirstOrDefault(p => timeToQuery >= p.StartTime &&
                                         timeToQuery <= p.EndTime);

Upvotes: 3

Pavel Radzivilovsky
Pavel Radzivilovsky

Reputation: 19104

Seems like a good solution to me as written. Alternatively, you could design your own range-based map.

Upvotes: 1

Related Questions