对象排序问题
我有一个 Car
集合:
var cars = new List<Car>();
cars.Add(new Car { ProductionDate = new DateTime(2011,02,02) });
cars.Add(new Car { ProductionDate = new DateTime(2011, 01, 01) });
cars.Add(new Car { ProductionDate = new DateTime(2011,04,04,04,04,04) });
cars.Add(new Car { ProductionDate = new DateTime(2011, 03, 03, 3, 3, 3) });
我需要按 ProductionDate
对它进行排序。
结果应该是,首先我将拥有带有日期和时间的汽车,因此应该是生产日期为 2011, 03, 03, 3, 3, 3 的汽车,最后应该是生产日期为 2011, 02, 02 的汽车生产日期。第二个应该是 2011, 04, 04, 04, 04, 04 的汽车,第三个应该是 2011, 02, 02 的汽车。
我可以使用 foreach
来做到这一点,但我相信有更好的方法做吧。
I have a collection of Car
:
var cars = new List<Car>();
cars.Add(new Car { ProductionDate = new DateTime(2011,02,02) });
cars.Add(new Car { ProductionDate = new DateTime(2011, 01, 01) });
cars.Add(new Car { ProductionDate = new DateTime(2011,04,04,04,04,04) });
cars.Add(new Car { ProductionDate = new DateTime(2011, 03, 03, 3, 3, 3) });
I need to sort it by ProductionDate
.
Result should be that at first I will have cars with date with time, so it should be car with 2011, 03, 03, 3, 3, 3 as production date, and at the end should be car with 2011, 02, 02 as production date. Second should be car with 2011, 04, 04, 04, 04, 04, and the third with 2011, 02, 02.
I can do it by using foreach
but I believe that there is nicer way to do it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我有类似的东西
,但看起来很丑。我希望看到更复杂的东西:)
I have something like that
but It looks ugly. I would like to see something more sophisticated :)
但请记住:如果汽车在 0:00 制造出来会发生什么?日期时间由数据+时间组成。你无法看到时间部分是否缺失!
我要补充的是,如果您需要使用
Enumerable.OrderBy
,那么您可以将我的 lamdba 函数与您可以在互联网上找到的LambdaComparer
一起使用(如建议的那样) sll)But remember: what happens if a car is built at 0:00? A DateTime is made of a Data+Time. You can't see if the Time part is missing!
I'll add that if you need to use the
Enumerable.OrderBy
, then you can use my lamdba function with theLambdaComparer
that you can find around the internet (as suggested by sll)