Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding max value from within List<T>

I have a number of objects defined, each has a property named "CreateDate".

Is it possible to write a single, generic method to select the highest date from an object that I specify?

I was attempting to use a generic approach to this, but the compiler doesn't like it when I try to specify a property name.

I was trying to achieve something along these lines...

private static DateTime GetLastDate<T>(List<T> data)
{
    // Unfortunately, this is not allowed...
    return
        (from d in data
        orderby d.CreateDate
        select d.CreateDate).FirstOrDefault();
}
like image 209
Rethic Avatar asked Nov 05 '12 20:11

Rethic


People also ask

How do you find the max of a list in a list?

The above syntax of max() function allows us to find the sum of list in list using the key=sum. max(list1, key=sum), this finds the list with maximum sum of elements and then sum(max(list1, key=sum)) returns us the sum of that list.

How can you retrieve the maximum value of a numeric list?

The max() Function — Find the Largest Element of a List. In Python, there is a built-in function max() you can use to find the largest number in a list. To use it, call the max() on a list of numbers. It then returns the greatest number in that list.

How do I find the max of a list in R?

In R, we can find the minimum or maximum value of a vector or data frame. We use the min() and max() function to find minimum and maximum value respectively. The min() function returns the minimum value of a vector or data frame. The max() function returns the maximum value of a vector or data frame.

What is the right syntax to find the maximum element in the list?

The max() function returns the item with the highest value, or the item with the highest value in an iterable.


1 Answers

The best method would be to create an interface with the specific functionality and have all of the classes implement that interface:

public interface ICreated
{
  public DateTime CreateDate {get;}
}

Then you can ensure that all of the items accepted implement that interface:

private static DateTime GetLastDate<T>(IEnumerable<T> input) where T : ICreated
{
    return input.Max(d=>d.CreateDate);
}

If that's really not an option (possibly because you can't modify the class to have it implement the interface or the collection to wrap the underlying type) you could use dynamic. I would highly discourage that you do this as it's really not good design, it will be much slower, and it's rather susceptible to breaking, but it could work:

private static DateTime GetLastDate(IEnumerable<dynamic> input)
{
    return input.Max(d=>d.CreateDate);
}
like image 165
Servy Avatar answered Sep 21 '22 05:09

Servy