如何使用日期列对数据表进行排序 [英] How to sort datatable with date column

查看:129
本文介绍了如何使用日期列对数据表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在获取一个包含日期列的数据表。日期显示为05-may-2015。我想要排序。我试过了。但是我得到的日值只是排序了。怎么解决这个..请回复.........谢谢

I am getting a datatable with columns containg date . The date is displayed like 05-may-2015. I want sort it . I tried .But i am getting the day value only sorted . How solve this.. Please reply .........Thanks

推荐答案

首先查看你的数据来源:你可能存储的是字符串中的日期值(或者当t =将它们提取到数据表中时将它们返回到字符串中)而不是使用正确的数据类型(C#的DateTime,SQL的DATETIME)。

因此,比较用于排序的是基于字符串的 - 它在第一个不同的字符处停止并将其用作整个比较的结果。

所以2015年4月12日将在12月2日之前-1999因为'A'在'F'之前 - 首先忽略字符串。



整理你的数据源!如果它是一个数据库,永远不会在字符串中存储日期或数值 - 当你试图使用实际数据时它总是会引起重大问题!
Start by looking at your data source: the chances are that you are storing your date values in strings (or returning them in strings when t=you fetch them into your datatable) instead of using the correct datatype (DateTime for C#, DATETIME for SQL).
As a result, the comparison which is used for sorting is string based - which stops at the first distinct character and uses that as the result for the whole comparison.
So "12-April-2015" will be before "12-February-1999" because 'A' is before 'F' - teh erst of the string is ignored.

Sort out your data source! And if it's a Database, never store date or numeric values in strings - it always causes major problems when you try to use the actual data!


试试这个



try this

table.Columns.Add("dateValue", typeof(DateTime?));

   var orderedRows = from row in dt.AsEnumerable()
                     orderby  row.Field<DateTime>("Date")
                     select row;
   DataTable tblOrdered = orderedRows.CopyToDataTable();


这篇关于如何使用日期列对数据表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆