c# - Searching each property value of an IQueryable collection of T against the value of a search query. How do I test for NOT NULL and CONTAINS together? -
i trying search each property value of iqueryable collection of t against value of search query. have following function , know how test not null , contains together?
private expression<func<t, bool>> propertysearch { { // object passed lambda expression parameterexpression instance = expression.parameter(typeof(t), "val"); expression whereexpr = expression.constant(true); // default val => true var _properties = typeof(t).getproperties(); foreach (var prop in _properties) { var query = _httprequest["query"].tolower(); var property = expression.property(instance, prop); var tostringcall = expression.call(expression.call( property, "tostring", new type[0]), typeof(string).getmethod("tolower", new type[0])); whereexpr = expression.and(whereexpr, expression.call(tostringcall, typeof(string).getmethod("contains"), expression.constant(query))); } return expression.lambda<func<t, bool>>(whereexpr, instance); }}
i have created search extensions nuget package performs type of check. example following.
note, without ide may have errors
/* *** start: these can made private reaonly fields ***/ var comparisonexpr = expression.constant(stringcomparison.ordinalignorecase); var zeroexpression = expression.constant(0) var nullexpression = expression.constant(null) methodinfo indexofmethod = typeof(string).getmethod("indexof", new[] { typeof(string), typeof(stringcomparison) }); /* *** end ***/ expression finalexpression = null parameterexpression instance = expression.parameter(typeof(t), "val"); var _properties = typeof(t).getproperties(); var query = _httprequest["query"].tolower(); var queryexpr = expression.constant(query); foreach (var prop in _properties) { //get property var propertyexpr = expression.property(instance, prop); //get property string var propstringexpr = expression.call(property, "tostring", new type[0]); //perform indexof call var indexofexpr = expression.call(propstringexpr, indexofmethod, queryexpr, comparisonexpr); // check index of greater or equal 0 var containsexpr = expression.greaterthanorequal(containsexpr, zeroexpression); if(finalexpression == null) { finalexpression = containsexp; } else { finalexpression = expression.andalso(containsexpr); } } return expression.lambda<func<t, bool>>(finalexpression, instance);
i've removed need tolower()
, instead used indexof
string comparison type
if want see how have achieved similar functionality, take @ ninjanye.searchextensions on github
https://github.com/ninjanye/searchextensions
if wanted search collection of iqueryable
use ninjanye.searchextensions follows
string query = _httprequest["query"]; var result = data.searchall().containing(query);
this search string properties (not properties have above) , return any property mathes search term.
hope helps
Comments
Post a Comment