问题1:在DateTime对象的集合中,如何确定哪一个是最早的/最新的?
问题2:在对象集合中,如何确定哪个对象具有最早/最新的DateTime属性?
例如:
class VideoGame
{
DateTime ReleaseDate { get; set; }
}
哪个VideoGame
会在第一个/最后一个发布?
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)} );
答案 0 :(得分:11)
使用LINQ的OrderBy和OrderByDescending函数:
VideoGame first= allGames.OrderBy(x => x.ReleaseDate).FirstOrDefault();
VideoGame last = allGames.OrderByDescending(x => x.ReleaseDate).FirstOrDefault();
答案 1 :(得分:3)
使用Linq?
var min = allGames.Min(s => s.ReleaseDate);
答案 2 :(得分:3)
var videoGame = allGames.OrderBy(x => x.ReleaseDate).FirstOrDefault(); earliest
var videoGame = allGames.OrderByDescending(x => x.ReleaseDate).FirstOrDefault(); latest
答案 3 :(得分:3)
问题1:
DateTime minDate = yourCollectionOfDateTimes.Min();
DateTime maxDate = yourCollectionOfDateTimes.Max();
或者,如果集合很大并且您不想迭代它两次以获得最小值和最大值:
DateTime? minDate = null, maxDate = null;
foreach (DateTime dt in yourCollectionOfDateTimes)
{
if ((minDate == null) || (dt < minDate.Value))
minDate = dt;
if ((maxDate == null) || (dt > maxDate.Value))
maxDate = dt;
}
问题2:
VideoGame oldest =
allGames.Aggregate((a, x) => x.ReleaseDate < a.ReleaseDate ? x : a);
VideoGame newest =
allGames.Aggregate((a, x) => x.ReleaseDate > a.ReleaseDate ? x : a);
或者,如果集合很大并且您不想迭代两次以获得最旧和最新的集合:
VideoGame oldest = null, newest = null;
foreach (VideoGame vg in allGames)
{
if ((oldest == null) || (vg.ReleaseDate < oldest.ReleaseDate))
oldest = vg;
if ((newest == null) || (vg.ReleaseDate > newest.ReleaseDate))
newest = vg;
}
答案 4 :(得分:-2)
您应该使用linq来获取最新版本。