Just define an interface like this
public interface IHaveAActivityPeriod { Boolean active { get; } DateTime? publishStart { get; } DateTime? publishEnd { get; } }
and add it to all relevant classes.
public class Foo : IHaveAActivityPeriod { [...] } public class Bar : IHaveAActivityPeriod { [...] }
Now you can use this extension method
public static class Extensions { public static Boolean IsActive(this IHaveAActivityPeriod item) { var now = DateTime.Now; return item.active && (item.publishStart <= now) (!item.publishEnd.HasValue || (item.publishEnd > now)); } }
for each instance that implements IHaveAActivityPeriod .
var foo = new Foo(); var isFooActive = foo.IsActive(); var bar = new Bar(); var isBarActive = bar.IsActive();
I completely missed the opportunity to build an extension method that filters the sequence instead of looking at one object at a time. Just take the extension method from flem, respond to the throw in the interface as a type constraint.
public static class Extensions { public IQueryable<T> IsActive<T>(this IQueryable<T> sequence) where T : IHaveAActivityPeriod { return source.Where(item => item.active && (item.publishStart <= now) && (!item.publishEnd.HasValue || (item.publishEnd > now)); } }
Daniel BrΓΌckner
source share