gpt4 book ai didi

linq - LINQ for LIKE查询数组元素

转载 作者:行者123 更新时间:2023-12-04 13:25:12 29 4
gpt4 key购买 nike

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

这样的事情会很甜蜜。

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


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

有任何想法吗?

最佳答案

实际上,这是我在“Express Yourself”演示文稿中使用的一个示例,该示例在常规LINQ中很难做到;据我所知,最简单的方法是手动编写谓词。我使用下面的示例(请注意,它对于StartsWith等同样适用):

    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 - LINQ for LIKE查询数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/698379/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com