开发者

Sorting a Dictionary by value which is an object with a DateTime

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:

public void List( Dictionary<string,DateTime> dict )
{
  int i = 0 ;
  foreach( KeyValuePair<string,DateTime> entry in dict.OrderBy( x => x.Value ).ThenByDescending( x => x.Key ) )
  {
    Console.WriteLine( "{0}. Key={1}, Value={2}" , ++i , entry.Key , entry.Value ) ;
  }
  Console.WriteLine( "The dictionary contained a total of {0} entries." , i ) ;
}

If on the other hand, you actually want/need an ordered collection, you need to spec out what your actual requirements are.


Dictionary are inherently unsorted. There are sorted implementations of IDictionary, but they are typically sorted by Key, not value (or attributes of the value). If you need the values sorted by the dt field of the value, you could do something like:

var valuesSorted = dict.Values.OrderBy(v=>v.dt);

But this eliminates the dictionary. I suspect that you need a different data structure, but we'd need to know more about the use case to be sure of what.


Based on your question and, others have pointed out, dictionaries aren't sorted, so the only logical way to return a sorted dictionary is to really return a sorted IEnumerable<KeyValuePair<String, Test>> instead. And doing this is easy.

var query =
    from kvp in dict
    orderby kvp.Value.dt
    select kvp;

You could easily change the select expression to return the value part of the KeyValuePair<,> or to return an anonymous type instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜