public static IQueryable <T> Search <T>(this IQueryable <T> source,
                                                string searchTerm,
                                                params Expression <Func <T, string> >[] stringProperties)
        {
            if (String.IsNullOrEmpty(searchTerm))
            {
                return(source);
            }

            var searchTermExpression = Expression.Constant(searchTerm);

            //Variable to hold merged 'OR' expression
            Expression orExpression = null;
            //Retrieve first parameter to use accross all expressions
            var singleParameter = stringProperties[0].Parameters.Single();

            //Build a contains expression for each property
            foreach (var stringProperty in stringProperties)
            {
                //Syncronise single parameter accross each property
                var swappedParamExpression = SwapExpressionVisitor.Swap(stringProperty, stringProperty.Parameters.Single(), singleParameter);

                //Build expression to represent x.[propertyX].Contains(searchTerm)
                var containsExpression = BuildContainsExpression(swappedParamExpression, searchTermExpression);

                orExpression = BuildOrExpression(orExpression, containsExpression);
            }

            var completeExpression = Expression.Lambda <Func <T, bool> >(orExpression, singleParameter);

            return(source.Where(completeExpression));
        }
예제 #2
0
 private IEnumerable <Expression <Func <TSource, TResult> > > AlignParameters <TSource, TResult>(Expression <Func <TSource, TResult> >[] properties, ParameterExpression parameterExpression)
 {
     for (int i = 0; i < properties.Length; i++)
     {
         var property = properties[i];
         yield return(SwapExpressionVisitor.Swap(property, property.Parameters.Single(), parameterExpression));
     }
 }
예제 #3
0
 /// <summary>
 /// Align the lambda parameter to that of the first string property
 /// </summary>
 protected Expression <TProperty> AlignParameter <TProperty>(Expression <TProperty> lambda)
 {
     return(SwapExpressionVisitor.Swap(lambda, lambda.Parameters.Single(), FirstParameter));
 }