Linq to Sql any keyword search query

前端 未结 1 828
野的像风
野的像风 2021-02-01 11:31

I have a case in my application where the user can search for a list of terms. The search needs to make three passes in the following order:

  • One for an exact match
1条回答
  •  后悔当初
    2021-02-01 11:40

    This might be a tough one... I think you'd have to write your own operator.

    (Update: Yep, I tested it, it works.)

    public static class QueryExtensions
    {
        public static IQueryable LikeAny(
            this IQueryable query,
            Expression> selector,
            IEnumerable values)
        {
            if (selector == null)
            {
                throw new ArgumentNullException("selector");
            }
            if (values == null)
            {
                throw new ArgumentNullException("values");
            }
            if (!values.Any())
            {
                return query;
            }
            var p = selector.Parameters.Single();
            var conditions = values.Select(v =>
                (Expression)Expression.Call(typeof(SqlMethods), "Like", null,
                    selector.Body, Expression.Constant("%" + v + "%")));
            var body = conditions.Aggregate((acc, c) => Expression.Or(acc, c));
            return query.Where(Expression.Lambda>(body, p));
        }
    }
    

    Then you could call this with:

    string[] terms = new string[] { "blah", "woo", "fghwgads" };
    var results = stuff.LikeAny(s => s.Title, terms);
    

    P.S. You'll need to add the System.Linq.Expressions and System.Data.Linq.SqlClient namespaces to your namespaces for the QueryExtensions class.

    0 讨论(0)
提交回复
热议问题