如何确定集合中最早/最新的DateTime? [英] How to determine the earliest/latest DateTime in a collection?
本文介绍了如何确定集合中最早/最新的DateTime?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题1:在DateTime对象的集合中,如何确定哪个对象是最早/最新的?
Question 1: In a collection of DateTime objects, how to determine which one is the earliest/latest?
问题2:在对象集合中,如何确定哪个对象具有最早/最新的DateTime属性?
Question 2: In a collection of objects, how to determine which object has the earliest/latest DateTime property?
例如:
class VideoGame
{
DateTime ReleaseDate { get; set; }
}
视频游戏
会首先发布/最后发布?
Which VideoGame
will be released first/last?
var allGames = new List<VideoGame>();
allGames.Add( new VideoGame() { ReleaseDate = new DateTime(2010, 10, 4)} );
allGames.Add( new VideoGame() { ReleaseDate = new DateTime(2012, 7, 14)} );
allGames.Add( new VideoGame() { ReleaseDate = new DateTime(2014, 5, 26)} );
推荐答案
使用LINQ的OrderBy和OrderByDescending函数:
Use the OrderBy and OrderByDescending functions of LINQ:
VideoGame first= allGames.OrderBy(x => x.ReleaseDate).FirstOrDefault();
VideoGame last = allGames.OrderByDescending(x => x.ReleaseDate).FirstOrDefault();
- 如果allGames的商品为零,则first和last将为null。
- 如果allGames有1个项目,则两个项目都将引用同一项目
这篇关于如何确定集合中最早/最新的DateTime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文