0

I'm using this search function. but I need it to do an "and" not an "or" I cant seem to get it to return the results I want. I need to perform a search function where the search results match the text entered in box. But only a partial search. For example if I type in "Super D" I want it to find everything that contains a "Super" AND a "D".

public static class ObjectContextExtensions {

    public static IQueryable<T> FullTextSearch<T>(this IQueryable<T> queryable, string searchKey)
    {
        return FullTextSearch<T>(queryable, searchKey, false);
    }

    public static IQueryable<T> FullTextSearch<T>(this IQueryable<T> queryable, string searchKey,
                                                  bool exactMatch)
    {

        ParameterExpression parameter = Expression.Parameter(typeof(T), "c");
        MethodInfo containsMethod = typeof(string).GetMethod("Contains", new Type[] { typeof(string) });
        // MethodInfo toStringMethod = typeof (object).GetMethod("ToString", new Type[] {});


        var publicProperties =
            typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
                      .Where(p => p.PropertyType == typeof(string));
        Expression orExpressions = null;
        string[] searchKeyParts;

        if (searchKey == null)
        {
            searchKey = "0";
        }
        searchKeyParts = !exactMatch ? searchKey.Split(' ') : new[] { searchKey };


        foreach (MethodCallExpression callContainsMethod in from property in publicProperties 
         select Expression.Property(parameter, property) into nameProperty 
         from searchKeyPart in searchKeyParts 

        let searchKeyExpression = Expression.Constant(searchKeyPart) let containsParamConverted = Expression.Convert(searchKeyExpression, typeof(string)) 

         select Expression.Call(nameProperty, containsMethod, (Expression)containsParamConverted))
        {
            if (orExpressions == null)
            {
                orExpressions = callContainsMethod;
            }
            else
            {
                orExpressions = Expression.Or(orExpressions,callContainsMethod);
            }
        }


        MethodCallExpression whereCallExpression = Expression.Call(
            typeof(Queryable),
            "Where",
            new Type[] { queryable.ElementType },
            queryable.Expression,
            Expression.Lambda<Func<T, bool>>(orExpressions, new ParameterExpression[] { parameter }));

        return queryable.Provider.CreateQuery<T>(whereCallExpression);
    }

}
4

1 回答 1

0

看起来将 exactMatch 设置为 true 可以解决问题,因为它不会拆分搜索词。

FullTextSearch<MyType>(searchKey, true)

做不到就换

orExpressions = Expression.Or(orExpressions,callContainsMethod);

andExpressions = Expression.And(andExpressions,callContainsMethod);
于 2013-07-19T16:21:57.217 回答