i created following rangefilter:
public class rangefilter<t> : ifilter<t> t : struct, iconvertible, icomparable { public t? maximum { get; private set; } public t? minimum { get; private set; } public rangefilter(t? minimum, t? maximum) { minimum = minimum; maximum = maximum; } public boolean matches(t value) { if (minimum != null && maximum != null) return value.compareto(minimum) >= 0 && value.compareto(maximum) <= 0; if (minimum == null && maximum != null) return value.compareto(maximum) <= 0; if (minimum != null && maximum == null) return value.compareto(minimum) >= 0; return false; } // matches } // rangefilter
which can used follows:
rangefilter<int32> filter = new rangefilter<int32>(2, 4); boolean match = filter.matches(2);
i need integrate extension:
public class product { public int32 rating { get; set; } } list<product> products = context.products.where(x => x.rating, filter);
so applying filter value of x.rating ...
i doing way because have multiple filter types implementing ifilter , few more things.
how can create extension?
public static class filterextensions { public static bool matches<t>(this t input, ifilter<t> filter) t : struct, iconvertible, icomparable { return filter.matches(input); } } list<product> products = context.products.where(x => x.rating.matches(filter));
which identical to
list<product> products = context.products.where(x => filter.matches(x.rating));
in comment added this:
because have multiple types of filter , inside extension determine type of filter according expression pass.
i'm not sure if warrants adding extension, since in case extension seems redundant.
if have expression in linq query determining filter use, query difficult read. extremely messy if determine need filter based on more 1 property.
based on i'd recommend defining filters entire class, not 1 property. have ifilter<t>
t
product
, not property of product
.
that enables write productfilter
class can unit test. when have 1 condition class simple. if have more conditions can modify productfilter
, inject collection of func<product, bool>
, run each product
through conditions.
i wouldn't recommend going out overkill right front. if take logic filters , isolate them separate classes accomplish few things:
- you can unit test filters
- if method requires filter can mock can test methods apart filters
- it easier read.
Comments
Post a Comment