简体   繁体   English

按日期类型以匿名类型对对象进行排序的好方法?

[英]Good way to sort object by date property in anonymous type?

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) 我猜这里肯定有更好的排序/排序方式,因为如果我有日期(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: 它仅按天排序,而不考虑月份,因此sortedArticles中的结果如下:

08.01.2011
10.02.2011
11.02.2011
12.01.2011
13.01.2011

I obviously want to display the latest article first, ie 11.02.2011 我显然想首先显示最新文章,即11.02.2011

Any suggestions? 有什么建议么?

Thanks in advance. 提前致谢。

The problem is that in your Select, you're calling ToString on your date field. 问题是在Select中,您正在日期字段上调用ToString As a result ArticleDate is being projected as a string . 结果,ArticleDate被投影为字符串 This is why it's not sorting correctly. 这就是为什么排序不正确的原因。

Projecting the ArticleDate as a nullable Date is probably your best bet 将ArticleDate投影为可为空的日期可能是最好的选择

var resultArticles = from a in articleItems 
select new
{
   Title = a.Title, 
   ArticleDate = a[Constants.FieldNames.ArticleStartDate] != null ?
     ((DateTime)a[Constants.FieldNames.ArticleStartDate]) : default(DateTime?),
   ByLine = a[Constants.FieldNames.Byline],
   FileRef = SPUtility.ConcatUrls(web.Url, a.Url)
};

Also, for something simple like this, you can use the more concise "dot notation" 另外,对于像这样的简单内容,您可以使用更简洁的“点符号”

var resultArticles = articleItems.Select(a => new { 
   Title = a.Title, 
   ArticleDate = a[Constants.FieldNames.ArticleStartDate] != null ?
     ((DateTime)a[Constants.FieldNames.ArticleStartDate]) : default(DateTime?),
   ByLine = a[Constants.FieldNames.Byline],
   FileRef = SPUtility.ConcatUrls(web.Url, a.Url)
};

At this point you can sort this collection by ArticleDate, which will be stored as a true Date, instead of a string 此时,您可以按ArticleDate排序此集合,该集合将存储为真实的Date,而不是字符串

resultArticles.OrderBy(a => a.ArticleDate).ToList();

Use the following syntax 使用以下语法

var q = from el in dataSource orderby el.SortField select new { 
    //your projection
};

The point here is to sort during the selection in one query. 这里的重点是在一个查询中进行选择时进行排序。

Edit 编辑

By using this statement you sort by actual DateTime and project string representation. 通过使用此语句,您可以按实际的DateTime和项目字符串表示形式进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM