7

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?

4 Answers 4

22

Linq Enumerable.Max should help you in this case

DateTime result = new[] { date1, date2, date3 }.Max();
1
  • seems much better than what i am doing. Let me check Commented Feb 29, 2016 at 7:17
3

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!

2

If you dont want to use Enumerable:

    var max = date1;
    if (date2 > max) max = date2;
    if (date3 > max) max = date3;
...

But I not recommend to go with this way.

0
if you have two dates then there is an inbuilt function in C#

    DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
          DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);
          int result = DateTime.Compare(date1, date2);
          string relationship;

          if (result < 0)
             relationship = "is earlier than";
          else if (result == 0)
             relationship = "is the same time as";         
          else
             relationship = "is later than";

          Console.WriteLine("{0} {1} {2}", date1, relationship, date2);



            List<List<string>> myList = new List<List<string>>();

            string[] words = new string[] { "trees", "bike", "cars", "steer", "arcs" };
            myList = GetAnagrams(words);

private List<List<string>> GetAnagrams(string[] words)
        {
            return words.GroupBy(w => new string(w.OrderBy(c => c).ToArray())).Select(group => group.ToList()).ToList();
        }
1
  • 1
    @fubo answer is preferable go for it, Thanks Commented Feb 29, 2016 at 7:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.