Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble Sorting a DATE column in DataTable/DataView in C#

I am trying to Sort a DataView in C#. It seems the Sort method of DataView Class takes the dates as strings.

In the output am getting this -

5/9/2013 4:56:38 PM
5/8/2013 4:23:06 PM
5/8/2013 1:38:21 PM
5/7/2013 9:55:30 PM
5/7/2013 7:54:45 PM
5/7/2013 7:44:10 PM
5/7/2013 7:44:10 PM
5/7/2013 12:26:38 PM
5/7/2013 1:44:06 PM
5/6/2013 4:08:54 PM
5/6/2013 10:32:49 AM
5/4/2013 7:54:23 PM
5/4/2013 12:57:21 PM
5/3/2013 3:49:03 PM
5/3/2013 3:49:03 PM
5/3/2013 2:06:12 PM
5/3/2013 11:19:34 AM
5/3/2013 11:03:32 AM
5/3/2013 1:58:38 PM
5/2/2013 7:27:55 PM
5/2/2013 7:17:50 PM
5/2/2013 7:06:06 PM
5/2/2013 6:42:37 PM
5/2/2013 6:30:58 PM
5/13/2013 12:49:24 PM

This is my code.

 DataTable dt;  
 DataView dv = dt.DefaultView;
 dv.Sort = "MessageDate desc";
 DataTable sortedDT = dv.ToTable();
 foreach (DataRow row in sortedDT.Rows)
 {
 code to print.
 }

As you can see the last date 5/13/2013 should be at the first and not at the bottom as 5/13 > 5/9 if its a date comparison, but 5/13<5/9 if you take it as a string.

MessageDate Column is datetime in my declaration, still the compiler is converting it to String.

 public struct Messages
    {
        public string ProfileId { get; set; }
        public string Network { get; set; }
        public string FromId { get; set; }
        public string FromName { get; set; }
        public string FromProfileUrl { get; set; }
        public DateTime MessageDate { get; set; }
        public string Message { get; set; }
        public string FbComment { get; set; }
        public string FbLike { get; set; }
        public string MessageId { get; set; }
        public string Type { get; set; }

    }

Any ideas why this is happening and how I can workaround the same?

like image 713
Sumit Ghosh Avatar asked May 14 '13 06:05

Sumit Ghosh


2 Answers

DataView stores date or anything as string type. Thus when you sort, it sort by string. To sort it as DateTime , you need to convert column to DateTime before adding any data, as follows,

dt.Columns["Date"].DataType = Type.GetType("System.DateTime");

like image 158
Mohsin Shaikh Avatar answered Oct 19 '22 22:10

Mohsin Shaikh


You need to implement IComparable to sort by DateTime: http://forums.asp.net/p/1267353/2393006.aspx

Alternatively, if you can change the struct, you can add a sorting value:

public string SortValue
{
    get
    {
        return ((int)((MessageDate - new DateTime(1970, 1, 1)).TotalSeconds)).ToString("D12");
    }
}

which converts the MessageDate to a seconds-since-epoch value, and then it can be lexicographically sorted.

like image 30
Elle Avatar answered Oct 19 '22 23:10

Elle