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)
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.
MaxDate(r=>r. ExpirationDate. Value); c#
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With