使用Linq过滤多级where子句

Phi*_*ray 4 c# linq linq-to-entities

假设我有一些过滤条件通过CustomerFilter对象数组传递到我的应用程序中,我需要运行查询并根据从Linq到Entities查询的过滤器返回结果.

因此,在这种情况下,客户将通过服务调用将一组CustomerFilter对象传递给我.

过滤对象:

class CustomerFilter
{
    public string CustomerID;
    public int[] LocationID;
}
Run Code Online (Sandbox Code Playgroud)

示例数据:

CustomerID    LocationID 

1             1

              2

              3

              4 

2             2 

              3 


              4
Run Code Online (Sandbox Code Playgroud)

我可以很容易地在外部CustomerID上构建查询过滤,如下所示.

查询:

    public void GetCustomerResults(List<CustomerFilter> accounts)
    {
        List<string> customer = (from a in accounts select a.CustomerID).ToList();

        var locations = ctx.Portal_SurveyLocations
                            .Where(w => customer.Contains(w.CustNum))
                            .OrderBy(o => o.LocationKey);
    }
Run Code Online (Sandbox Code Playgroud)

所以我可以按外部标准进行筛选,但我不确定如何根据每个CustomerID的多个位置ID进行筛选.显然只是放置一个OR子句会产生不正确的结果,因为它会引入具有匹配LocationID的其他CustomerID.

在传入CustomerFilter对象的情况下,如何实现此多级过滤器的任何想法?

mat*_*mmo 5

轻微返工.基本上,我们使用组合Any来遍历子集合以实现期望的结果.

var locations = ctx.Portal_SurveyLocations
    .Where(w => accounts.Any(a => a.CustomerID == w.CustNum &&
                                  a.LocationID.Any(l => w.LocationKey == l)))
    .OrderBy(o => o.LocationKey);
Run Code Online (Sandbox Code Playgroud)

  • @mattytommo我调整了你的代码,因为你试图在两个不同的范围内使用一个名为`w`的变量:你有`Where`lambda以及`a.LocationID.Any`一个,所以它正在生成@ PhilMurray的编译错误.我相信这应该可以解决这个问题. (2认同)