I have a struct Test, which I add as a value to a dictionary.
What I want to do is sort the dictionary by the DateTime of the value.
struct Test
{
DateTime dt;
public string ID;
}
Dictionary<String, Test> dict = new Dictionary<String,Test>();
Test t = new Test();
t.dt = DateTime.Now;
t.ID = "XUDF";
dict.Add(t.ID, t);
t.dt = DateTime.Now.AddDays(17);
t.ID = "RFGT";
dict.Add(t.ID, t);
t.dt = DateTime.Now.AddDays(3);
t.ID = "ADLV";
dict.Add(t.ID, t);
t.dt = DateTime.Now.AddHours(2);
t.ID = "SKFU";
dict.Add(t.ID, t);
I’m not sure what to do after this.
Also, is this the best way to go about it?
I’m using .net 3
What I am trying to do is have a list that I can access by the ID but also ordered by the datetime in t.dt.
I want to be able to select an object by its ID but also be able to iterate through and have it come out in order of datetime.
What do you mean by “sort the dictionary”? A dictionary has no “order” to it per se. It’s a keyed collection, the underlying implementation of which is a hash table.
I assume what you meant to say is, “I want to enumerate over the contents of the dictionary in order of the values.” That can be done thusly:
If on the other hand, you actually want/need an ordered collection, you need to spec out what your actual requirements are.