Dataview按月和日排序日期

时间:2016-06-27 15:58:26

标签: sql sorting dataview

我希望按天和月对DataView进行排序,以便为组织创建生日列表,并期待使用DatePart进行排序。我可以在SQL中实现这一点,但排序顺序不会从返回的结果中持久存储到数据视图中,并且使用此功能不会起作用。

DataTable dt = dsResults.Tables[1];
DataView dv = new DataView(dt);

dv.Sort = "DATEPART(Month, birthdate),DATEPART(Day, birthdate)";
dt = dv.ToTable();

我对数据视图或排序方法不太熟悉,所以感谢任何帮助

1 个答案:

答案 0 :(得分:0)

DataView.Sort()将根据列中的数据类型进行排序。 诀窍是将正确格式化的临时列添加到数据表中以进行排序。

此临时列方法比您预期的要快。

扩展上述问题的代码 例如:

DataTable dt = dsResults.Tables[1];

//add a sorting column
dt.Columns.Add(new DataColumn("SortySortColumn", typeof(string)));

//enumerate all the rows 
DateTime oTMPdate;
foreach (DataRow oDR in oDT.Rows)
{
    //test for date, if date convert to two letter month, two letter day
    //  add that value to the sorting column
     if(DateTime.TryParse(oDR["birthdate"], out oTMPdate)
         oDR["SortySortColumn"] = string.Format("{0:MMdd}", oTMPdate);
}       

//sort by our new temporary column
DataView dv = new DataView(dt);
dv.Sort = "[SortySortColumn] ASC";
dt = dv.ToTable();

//remove the temporary column
dt.Columns.RemoveAt(dt.Columns.Count - 1);

不要忽视string.Format()的力量,你可以用它来做很多事情。 : - )

相关问题