Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting object with max date time value in one of it's properties

Tags:

c#

linq

When I want to retrieve an object with the highest value in a DateTime property from an IEnumerable, I can do the following:

var maxDate = myEnumerable.Max(x => x.TheDateTimeProperty);
var wantedObject = myEnumerable.FirstOrDefault(x => x.TheDateTimeProperty == maxDate);

Is this possible without getting the maxDate first? For example like this:

var wantedObject = myEnumerable.GetByMaxDate(x => x.TheDateTimeProperty);

I know that I could write an extension method GetByMaxDate, but I want to know if there is already a method provided by linq.

Just to clarify: Not looking for other possibilities to write this. I was just interested if there exists a method that does it. (less code, best performance possible managed by the method)

like image 935
Philipp M Avatar asked Mar 11 '13 09:03

Philipp M


People also ask

What is DateTime max value?

Remarks. The value of this constant is equivalent to 23:59:59.9999999 UTC, December 31, 9999 in the Gregorian calendar, exactly one 100-nanosecond tick before 00:00:00 UTC, January 1, 10000.

How do I get the latest date in C#?

MaxDate(r=>r. ExpirationDate. Value); c#

How do you find the max date in a list?

Getting Object with Max date using Stream.max() method. In this way, we can get a custom object from a List of objects while comparing the date values from one of its fields.

How do I find the max date in a list of dates using Java?

To get max or min date from a stream of dates, you can use Comparator. comparing( LocalDate::toEpochDay ) Comparator. The toEpochDay() function returns the count of days since epoch i.e. 1970-01-01.


2 Answers

Pro : it should work with "any" linq provider (objects, entities, sql)

myEnumerable.OrderByDescending(x => x.TheDateTimeProperty).First();

Con : as pointed by Matthew Watson in comments, it won't be performant on (very) large lists.

like image 91
Raphaël Althaus Avatar answered Oct 13 '22 20:10

Raphaël Althaus


I prefer to get the maxDate first like you have stated originally. I don't see any problem using the syntax you already used.

However if want you can shorthand the code like this:

var wantedObject = myEnumerable.FirstOrDefault(x => x.TheDateTimeProperty == myEnumerable.Max(x => x.TheDateTimeProperty));

(This code is not tested, maybe some type casting is needed)

Or you can write a stored procedure and take the data from that.

However I don't prefer OrderByDescending.First anymore. It is fine if physically your data in table is sorted ascending by your specified property. But if not, then your sql table will need to do descending sorting and probably get high load from it. Especially when the table has over than 1m record and the DateTime is stored ascending in the physical.

Use max can resulting better (faster/lightweight) result than it.

like image 31
Fendy Avatar answered Oct 13 '22 20:10

Fendy