I have the following code:
var resultArticles = from a in articleItems
select new
{
Title = a.Title,
ArticleDate = a[Constants.FieldNames.ArticleStartDate] != null ?
((DateTime)a[Constants.FieldNames.ArticleStartDate]).ToString(Constants.Date.Format): string.Empty,
ByLine = a[Constants.FieldNames.Byline],
FileRef = SPUtility.ConcatUrls(web.Url, a.Url)
};
var sortedArticles = resultArticles.OrderBy(a => a.ArticleDate).ToList();
rptArticles.DataSource = sortedArticles;
rptArticles.DataBind();
I guess there must be a better way to sort/order here because if I have the dates (dd/mm/yyy)
12.01.2011
11.02.2011
10.02.2011
13.01.2011
08.02.2011
it only sorts by the day and don’t take the month into consideration so the result in sortedArticles is as follows:
08.01.2011
10.02.2011
11.02.2011
12.01.2011
13.01.2011
I obviously want to display the latest article first, i.e. 11.02.2011
Any suggestions?
Thanks in advance.
The problem is that in your Select, you’re calling
ToStringon your date field. As a result ArticleDate is being projected as a string. This is why it’s not sorting correctly.Projecting the ArticleDate as a nullable Date is probably your best bet
Also, for something simple like this, you can use the more concise “dot notation”
At this point you can sort this collection by ArticleDate, which will be stored as a true Date, instead of a string