实施“类似”运营商多次在一个Linq到实体查询 [英] Implementing a "like" operator multiple times in one Linq to Entities query

查看:161
本文介绍了实施“类似”运营商多次在一个Linq到实体查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个字符串列表,我们需要通过该列表过滤我们的结果。例如,可以找到所有拥有SSN的学生,从465,496或497开始(再加上x)

We have a list of strings and we need to filter our results by that list. Example would be find all students who have SSNs that start with 465, 496, or 497 (plus x more)

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,
    ...
}

代码提供了这里接近我们需要的,但是我们无法弄清楚如何使用Expression Class来使用StartsWith。

The code provided here is close to what we need, but we can't figure out how to impliment the StartsWith that we need using the Expression Class.

推荐答案

嗯,你可以尝试这个:

Well, you could try this:

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

这可能不起作用,但在进入之前值得尝试任何更复杂的东西。

That may well not work, but it would be worth trying before you go into anything more complicated.

编辑:正如你所说,上面的代码不会编译 - 你基本上需要构建一个表示树,表示 where 子句。哎呀。但是,在开始这样做之前,最好先看看它是否会有效。尝试这样:

As you say, the above won't compile - you basically need to build an expression tree representing the bit within the Where clause. Oops. However, before you start doing that, it would be worth seeing whether it'll work in the end. Try this:

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,
    ...
}

如果不行,那么做一个更通用的方法将不会有任何用处:(

If that doesn't work, then making a more general method won't be any use :(

这篇关于实施“类似”运营商多次在一个Linq到实体查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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