LINQ 用于数组元素的 LIKE 查询 [英] LINQ for LIKE queries of array elements

查看:14
本文介绍了LINQ 用于数组元素的 LIKE 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数组,我想对 varchar 执行 LINQ 查询,该查询返回在 varchar 的任何位置具有数组元素的任何记录.

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.

这样的事情会很甜蜜.

<代码>string[] 行业 = {航空公司",铁路"}

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

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

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

有什么想法吗?

推荐答案

这实际上是我在表达自己" 演示文稿,用于在常规 LINQ 中难以做到的事情;据我所知,最简单的方法是手动编写谓词.我使用下面的例子(注意它同样适用于 StartsWith 等):

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);
    }

}

这篇关于LINQ 用于数组元素的 LIKE 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆