LINQ按日期降序排列对象集合 [英] LINQ order a collection of objects by date in descending order

查看:70
本文介绍了LINQ按日期降序排列对象集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆对象(产品),我想按降序创建的日期先对它们进行排序,然后仅显示前10条记录.创建日期(DateTime)的格式如下.

I have a bunch of objects(products) and I want to order them by date created in descending order first and then only display the top 10 records. The format of the date created(DateTime) is as as follow.

4/4/2007 12:00:00 AM

这是我尝试过的.

如何按日期降序排列前10名?

How can I sort the top 10 in descending order by date?

var productLatestReleases = (from p in visualsProduct
                                 from pf in p.DomainObjectFields
                                 select p).Distinct().OrderByDescending(d => d.DateCreated).Take(10); 

推荐答案

由于您正在描述日期的格式,因此我认为 DateCreated 属性的数据类型为 string .如果是这样,您可以执行以下操作:

Since you are describing the format of the date, I suppose that the datatype of the DateCreated property is string. If it is then you could do:

.OrderByDescending(d => Convert.ToDateTime(d.DateCreated)).Take(10)

此外,如果您未指定要比较的相等性,则您的 Distinct()不会有太大效果.

Also, your Distinct() will not have much effect if you don't specify your own equality to compare.

这篇关于LINQ按日期降序排列对象集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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