Lalchand
Lalchand

Reputation: 7827

Need to sort Datetime

I need to store collection of Inputtime(DateTime) and OutPutTime(Datetime) in variable then need to sort based upon input time.

What to use Dictionary,or ..?

Upvotes: 1

Views: 187

Answers (2)

tzaman
tzaman

Reputation: 47790

Make a holder class (or just use an anonymous type - or a Tuple if you're using .NET4), add them to a List, then use LINQ. Something like this:

class Timeslot
{
    public DateTime InputTime { get; set; }
    public DateTime OutputTime { get; set; }
}

public static void Main()
{
    var timeList = new List<Timeslot>(); 
    //populate the list
    var sortedList = timeList.OrderBy(t => t.InputTime).ToList();
}

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500515

Dictionary<TKey, TValue> is unordered, so no - don't use that.

Options:

  • If you're using .NET 4.0, you could use a Tuple<DateTime, DateTime> for each item
  • If it's all within one method, you could use an anonymous type
  • You could create your own struct or class to hold the pair of "input time, output time"

However you do it, you would then use OrderBy from LINQ and then call ToList or ToArray if necessary, or create a List<T> and then call Sort with an appropriate comparator.

You could use SortedList<,> or SortedDictionary<,> but unless you actually need to look end times up by start times (instead of just iterating over them) these seem like inappropriate abstractions to me.

Upvotes: 2

Related Questions