I have a generic extension method for validating my entities. The main idea is to be able to specify at runtime (context related) the criteria for validating a specific entity (with the end goal of saving it in the data base).
public static Boolean IsValidEntity<T>(this T entity, List<Predicate<T>> predicates)
{
Boolean res = true;
predicates.ForEach(p => res &= (Boolean)p.DynamicInvoke(entity));
return res;
}
Inside my repository I can then use (simplified as this is not the scope but is somewhat necessary for the question context):
public void SaveIntProperty(int myProperty, List<Predicate<int>> predicates)
{
if (myProperty.IsValidEntity<int>(predicates))
{
//save to data base or other actions
}
}
A simple example on a list of int
s would be to search for elements which (in a particular context) need to be both even and less than 8.
List<int> numbers = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
//dynamically create the validation criteria
List<Predicate<int>> predicates = new List<Predicate<int>>();// List<Delegate>();
Predicate<int> lessThan = x => x < 8;
predicates.Add(lessThan);
Predicate<int> even = x => x % 2 == 0;
predicates.Add(even);
numbers.ForEach(n => SaveIntProperty(n, predicates));
The IsValidEntity
extension method works and looks simple enough. However, I'm having doubts about the performance and the extensibility. Is the use of the ForEach
ok? Should I pass the predicates differently? Should I use something else instead of predicates?
List.ForEach()
, just use a normalforeach
, it's actually even few characters shorter. – svick Mar 13 '14 at 13:24