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

c#, linq

Solution

Since there are coming no other answers and there doesn't exist a build-in method in linq, I'll write down what I would use.

For linq to objects:

The method `MaxBy` from morelinq as mentioned by Habib in the comment.

For linq to sql:

I would write an extension method:

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

Update:

In the .NET 9 Preview there was added a MaxBy method.

Problem

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)

Original source