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 best method would be to create an interface with the specific functionality and have all of the classes implement that interface:
Then you can ensure that all of the items accepted implement that interface:
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: