Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ for LIKE queries of array elements

Let's say I have an array, and I want to do a LINQ query against a varchar that returns any records that have an element of the array anywhere in the varchar.

Something like this would be sweet.

string[] industries = { "airline", "railroad" }

var query = from c in contacts where c.industry.LikeAnyElement(industries) select c

Any ideas?

like image 252
Clark Avatar asked Mar 30 '09 18:03

Clark


1 Answers

This is actually an example I use in my "Express Yourself" presentation, for something that is hard to do in regular LINQ; As far as I know, the easiest way to do this is by writing the predicate manually. I use the example below (note it would work equally for StartsWith etc):

    using (var ctx = new NorthwindDataContext())
    {
        ctx.Log = Console.Out;
        var data = ctx.Customers.WhereTrueForAny(
            s => cust => cust.CompanyName.Contains(s),
            "a", "de", "s").ToArray();
    }
// ...
public static class QueryableExt
{
    public static IQueryable<TSource> WhereTrueForAny<TSource, TValue>(
        this IQueryable<TSource> source,
        Func<TValue, Expression<Func<TSource, bool>>> selector,
        params TValue[] values)
    {
        return source.Where(BuildTrueForAny(selector, values));
    }
    public static Expression<Func<TSource, bool>> BuildTrueForAny<TSource, TValue>(
        Func<TValue, Expression<Func<TSource, bool>>> selector,
        params TValue[] values)
    {
        if (selector == null) throw new ArgumentNullException("selector");
        if (values == null) throw new ArgumentNullException("values");
        if (values.Length == 0) return x => true;
        if (values.Length == 1) return selector(values[0]);

        var param = Expression.Parameter(typeof(TSource), "x");
        Expression body = Expression.Invoke(selector(values[0]), param);
        for (int i = 1; i < values.Length; i++)
        {
            body = Expression.OrElse(body,
                Expression.Invoke(selector(values[i]), param));
        }
        return Expression.Lambda<Func<TSource, bool>>(body, param);
    }

}
like image 152
Marc Gravell Avatar answered Oct 30 '22 13:10

Marc Gravell