If you want to apply this method to multiple entities, you have to introduce an interface that contains the relevant properties, an extension method that works on that interface and apply the interface to the relevant entities.
So:
public interface IHasTimestamps
{
DateTime Created { get; set; }
DateTime? LastUpdated { get; set; }
}
public class Foo : IHasTimestamps
{
public DateTime Created { get; set; }
public DateTime? LastUpdated { get; set; }
}
public class Bar : IHasTimestamps
{
public DateTime Created { get; set; }
public DateTime? LastUpdated { get; set; }
}
Now you can create a generic extension method that accepts an IQueryable<T>
, with T
constrained to that interface, allowing you to access those properties:
public static class EntityExtensions
{
public static IOrderedQueryable<TEntity> OrderByTimestampsDescending<TEntity>(this IQueryable<TEntity> query)
where TEntity : IHasTimestamps
{
return query.OrderByDescending(q => q.LastUpdated ?? q.Created);
}
}
And call it like that:
var list = new List<Foo>
{
new Foo { Created = new DateTime(2020, 09, 03) },
new Foo { LastUpdated = new DateTime(2020, 09, 04) },
new Foo { Created = new DateTime(2020, 09, 05), LastUpdated = new DateTime(2020, 09, 06) },
}.AsQueryable();
var sorted = list.OrderByTimestampsDescending().ToList();
foreach (var s in sorted)
{
Console.WriteLine(s.Created + " " + s.LastUpdated);
}
So now you can call OrderByTimestampsDescending()
on any IQueryable<T>
where that T
implements said interface, and have your results sorted.