How to determine the earliest / latest date in a collection?

Question 1: In a collection of DateTime objects, how do I determine which one is the earliest / latest?

Question 2: In a collection of objects, how to determine which object has the earliest / latest DateTime property?

For example:

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)} ); 
+7
source share
5 answers

Use the OrderBy and OrderByDescending LINQ functions:

 VideoGame first= allGames.OrderBy(x => x.ReleaseDate).FirstOrDefault(); VideoGame last = allGames.OrderByDescending(x => x.ReleaseDate).FirstOrDefault(); 
  • If allGames has null elements, the first and last will be empty.
  • If allGames has 1 element, both elements will refer to the same element.
+8
source
 var videoGame = allGames.OrderBy(x => x.ReleaseDate).FirstOrDefault(); earliest var videoGame = allGames.OrderByDescending(x => x.ReleaseDate).FirstOrDefault(); latest 
+3
source

Use Linq?

 var min = allGames.Min(s => s.ReleaseDate); 
+2
source

Question 1:

 DateTime minDate = yourCollectionOfDateTimes.Min(); DateTime maxDate = yourCollectionOfDateTimes.Max(); 

Or if the collection is large and you do not want to repeat it twice to get min and 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; } 

Question 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); 

Or, if the collection is large, and you do not want to repeat it twice to get the oldest and latest:

 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; } 
+2
source

You must use linq to get the latter.

0
source

All Articles