1

In a C# / WPF application I have a list of type string that is the ItemsSource of a combobox. This list contains half-hour chunks of time that are free on the user's calendar for the current day (from 8am to 5pm). Pictured here:

enter image description here

I would like to trim the list so that times in the past are not shown (e.g. If it's presently 10am, don't show chunks of time from 8am-10am). How can I best accomplish this?

Update: The list of strings is composed of "startTime" + " - " + "endTime", so each entry in the list looks like:

6/10/2014 8:00:00 AM - 6/10/2014 8:30:00 AM
6/10/2014 8:30:00 AM - 6/10/2014 9:00:00 AM
etc...
user3342256
  • 1,238
  • 4
  • 21
  • 35

2 Answers2

2

I figured it out by using a bit of lambda expressions. Say your list of times is called:

times

then using the where clause, we can then get all the times after now by using:

List<string> ordered = times.Where(o => DateTime.Parse(o.Split('-')[1]) > DateTime.Now).ToList();

This basically parses each element in your 'times' list into a DateTIme type and then sees if it is after the current DateTime.

Elias
  • 1,367
  • 11
  • 25
  • That's really slick and is almost perfect, however because it's evaluating both DateTime objects on either side of "-" it's still returning some unusable times. For instance if it's 9:15am, you'd still see an item indicating you're available from 9:00 - 9:30 because 9:30 isn't in the past. To fix this, you'd just need to evaluate times on the left of the hyphen character. How could your expression be re-written to do that? – user3342256 Jun 10 '14 at 16:10
  • You would change `o.Split('-')[1]` to `o.Split('-')[0]` to evaluate the left hand time – Elias Jun 10 '14 at 16:12
1

Using LinQ is usually the easiest way to filter a collection. Clearly however, this is going to be far more difficult if you stick with string values, so I'm going to look at this from a different angle - just recreating the collection each two hours. In this case, the filtering would be unnecessary... try something like this:

List<DateTime> validDates = new List<DateTime>();
DateTime startTime = DateTime.Now.Date;
for (int index = 0; index < 48; index++)
{
    if (startTime > DateTime.Now)
    {
        validDates.Add(startTime);
    }
    startTime = startTime.AddMinutes(30);
}

I'll leave it up to you how you want to populate your string values from these valid DateTime instances.

Sheridan
  • 68,826
  • 24
  • 143
  • 183