开发者_运维知识库Question 1: In a collection of DateTime objects, how to 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)} );
Use the OrderBy and OrderByDescending functions of LINQ:
VideoGame first= allGames.OrderBy(x => x.ReleaseDate).FirstOrDefault();
VideoGame last = allGames.OrderByDescending(x => x.ReleaseDate).FirstOrDefault();
- If allGames has zero items, both first and last will be null.
- If allGames has 1 item, both items will reference that same item
Use Linq?
var min = allGames.Min(s => s.ReleaseDate);
var videoGame = allGames.OrderBy(x => x.ReleaseDate).FirstOrDefault(); earliest
var videoGame = allGames.OrderByDescending(x => x.ReleaseDate).FirstOrDefault(); latest
Question 1:
DateTime minDate = yourCollectionOfDateTimes.Min();
DateTime maxDate = yourCollectionOfDateTimes.Max();
Or, if the collection is large and you don't want to iterate through it twice to get the 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 don't want to iterate through it twice to get the oldest and newest:
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;
}
You should use linq to to get tha latest one.
精彩评论