我们有一个字符串列表,我们需要根据该列表过滤我们的结果。示例是查找所有 SSN 以 465、496 或 497(再加上 x 个)开头的学生
List<string> list = GetPossibleStartsWithValues();
var qry = from student in entities.Students.WhereStartsWith(x=>x.SSN, list)
select new SearchedStudent
{
Name = student.Name,
SSN = student.SSN,
...
}
提供的代码here接近我们需要的,但是我们无法弄清楚如何使用表达式类来实现我们需要的 StartsWith。
最佳答案
好吧,你可以试试这个:
public static IQueryable<T> WhereStartsWith<T>(this IQueryable<T> source,
Expression<Func<T, string>> projection,
List<T> list)
{
return source.Where(x => list.Any(y => projection(x).StartsWith(y)));
}
这可能行不通,但在您进入任何更复杂的领域之前值得尝试。
编辑:正如您所说,上面的代码不会编译 - 您基本上需要构建一个表达式树来表示 Where
子句中的位。哎呀。但是,在您开始这样做之前,值得看看它最终是否会起作用。试试这个:
List<string> list = GetPossibleStartsWithValues();
var qry = from student in entities.Students
.Where(student => list.Any(y => student.SSN.StartsWith(y)))
select new SearchedStudent
{
Name = student.Name,
SSN = student.SSN,
...
}
如果这不起作用,那么制作一个更通用的方法将没有任何用处:(
关于c# - 在一个 Linq to Entities 查询中多次实现 "like"运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3660557/