Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding latest date from multiple dates

Tags:

c#

I have three dates

DateTime date1 = st.UpdatedDate;
DateTimed date2 = cl.updatedDate;
DateTime date3 = d.UpdatedDate;

I am comparing and finding latest date as following...

if (date1 > date2 &&  date1 > date3 )
   latestDate = date1;
else if (date2 > date1 &&  date2 > date3 )
  latestDate = date2 ;
else
  latestDate = date3;

I wonder and would like to ask whether there is any built-in method that can compare multiple dates and tell me the greatest date?

like image 454
immirza Avatar asked May 06 '26 19:05

immirza


2 Answers

Linq Enumerable.Max should help you in this case

DateTime result = new[] { date1, date2, date3 }.Max();
like image 175
fubo Avatar answered May 09 '26 07:05

fubo


Honorable mention to Enumerable.OrderByDescending(date => date).First() (or OrderBy().Last()). Does more than needed, but in some cases it's required, and it felt very much so related!

like image 37
sara Avatar answered May 09 '26 07:05

sara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!