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();
}
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.
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.
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.
The max() function returns the item with the highest value, or the item with the highest value in an iterable.
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);
}
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