Getting an object with the maximum date time value in one of its properties

When I want to get the object with the highest value in the DateTime property of 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 maxDate first? For example, for example:

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

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

Just to clarify: Do not look for other ways to write this. I was just wondering if there is a method that does this. (less code, best performance can be controlled by method)

+7
source share
3 answers

Since there are no other answers, and there is no built-in method in linq, I will write what I will use. p>

For linq for objects:

The MaxBy method from morelinq , as mentioned by Habib in a comment.

For linq to sql:

I would write an extension method. I tried this, but the following code still does not work. If anyone knows what is wrong, edit the answer. I will try to understand this when I have time.

 public static TSource SqlMaxBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) { var maxValue = source.Max(selector); return source.FirstOrDefault(selector == maxValue); } 
0
source

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

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

Con: as stated in the comments by Matthew Watson, he will not execute (very) large lists.

+10
source

I prefer to get maxDate first, as you originally stated. I do not see any problems using the syntax that you already used.

However, if you want, you can shorten the code as follows:

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

(This code is not verified, some casting may be required)

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

However, I do not prefer OrderByDescending. At first. This is normal if physically your data in the table is sorted by your specified property. But if not, then your sql table will need to sort the sort and probably get a big load. Especially if the table has more than 1 m of records, and DateTime is stored in ascending order in the physical.

Using max can lead to a better (faster / easier) result than to it.

+2
source

All Articles