LINQ的数组元素的LIKE查询 [英] LINQ for LIKE queries of array elements
问题描述
比方说,我有一个数组,我希望做一个LINQ查询对返回那些在VARCHAR任何地方数组的元素任何记录一个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[] industries = { "airline", "railroad" }
VAR的查询=从C中的联系人那里c.industry.LikeAnyElement(行业)选择C
var query = from c in contacts where c.industry.LikeAnyElement(industries) select c
任何想法?
推荐答案
这其实是我在的防爆preSS自己presentation,的东西,是很难在常规的LINQ做;据我所知,要做到这一点最简单的方法是手动编写predicate。我用下面的例子(注意它会为 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屋!