开发者

C# sorting List key value pair by a date string

Solved.

The string for the keyvalue pair

List<KeyValuePair<string, string>> responses = new List<KeyValuePair<string, string>>();

Is like so: 2011-6-8 2:19:0 || url

I sorted the List by using the following:

responses.OrderByDescending(s => DateTime.Parse(s.Key.Split(new string[] { " || " }, StringSplitOptions.None)[0])).ToList();

Thanks for the quick responses everyone.

Problem:

I have a list that contains a key value pair like so:

List<KeyValuePair<string, string>> responses = new List<KeyValuePair<string, string>>();

The string key will be a concatenated string of a date time stamp, and a url. For example: 2011-6-8 2:19:0 - http://google.com/?q=somesearch

The following sort works to a point, but the day value is sorted by string, not by number (not unexpected).

With this code:

responses.OrderByDescending(s => s.Key).ToList();

I'll have something like:

2011-6-8 2:19:0 - url
2011-6-8 12:18:0 - url
2011-6-7 12:29:0 - url 
20开发者_运维知识库11-6-6 17:42:0 - url
2011-6-6 12:39:0 - url
2011-6-5 10:31:0 - url
2011-6-3 20:53:0 - url
2011-6-21 9:1:0 - url

Any ideas on how to sort this correctly?


Just add leading zeros to your date format:

dateTime.ToString("yyyy-MM-dd");

Other option (not sure whether you can do it) is to sort records in advance, before converting date to string.


I agree with the above answers, if you can control the input, you should change it. If you can't change the key values, I would split the string - re-build it in a better format and sort that.

Maybe something like this could work (you would have to put it back together in order after sorting):

Dictionary<DateTime, string> sortableKeys = new Dictionary<DateTime, string>();
foreach (string key in responses.Keys)
{
   string[] keySplit = key.Split(" - ");
   sortableKeys.Add(DateTime.Parse(keySplit[0], key));            
}

Untested... :)


You should store as a Date/Time structure or have a sortable string with 0 padded month, day, hours, minutes, and seconds (e.g. 2011-06-06 09:21:03)


I would cast your Key to a DateTime in OrderByDescending Func and use the built in DateTime.Compare to perform the sort.

This doesn't handle errors obviously if the string isn't actuall a valid DateTime but it will do the right thing without any string hacks

responses.OrderByDescending(kvp => DateTime.Parse(kvp.Key));
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜