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

I am trying to sort a DataView in C #. It seems that the Sort method of the DataView class accepts dates as strings.

At the output, I get 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 of 17/13/2013 should be the first, not the bottom, like 5/13> 5/9 if it is a date comparison, but 5/13 <5/9 if you take it as a string.

The MessageDate column is the datetime in my declaration, but the compiler converts 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 get around this?

+6
source share
2 answers

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

Alternatively, if you can change the structure, you can add a sort value:

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

which converts MessageDate to a second value, starting from the-epoch, and then it can be lexicographically sorted.

+1
source

A DataView stores a date or something as a row type. Thus, when sorting, it is sorted by row. To sort it as a DateTime, you need to convert the column to DateTime before adding any data, as shown below:

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

+1
source

Source: https://habr.com/ru/post/944948/


All Articles